Example usage for org.eclipse.jgit.diff DiffAlgorithm diff

List of usage examples for org.eclipse.jgit.diff DiffAlgorithm diff

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff DiffAlgorithm diff.

Prototype

public <S extends Sequence> EditList diff(SequenceComparator<? super S> cmp, S a, S b) 

Source Link

Document

Compare two sequences and identify a list of edits between them.

Usage

From source file:com.googlesource.gerrit.plugins.serverconfig.UnifiedDiffer.java

License:Apache License

public String diff(RawText v0, RawText v1) throws IOException {
    DiffAlgorithm algorithm = MyersDiff.INSTANCE;

    EditList editList = algorithm.diff(RawTextComparator.DEFAULT, v0, v1);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (DiffFormatter formatter = new DiffFormatter(os)) {
        formatter.format(editList, v0, v1);
    }/*  w ww.  j a v a 2s.c o m*/

    return os.toString(CHARSET_NAME);
}

From source file:models.FileDiffTest.java

License:Apache License

@Test
public void getHunks() throws IOException {
    // given//  w w  w .  j av  a2 s  .c o m
    FileDiff fileDiff = new FileDiff();
    fileDiff.a = new RawText("apple\nbanana\ncat\n".getBytes());
    fileDiff.b = new RawText("apple\nbanana\ncorn\n".getBytes());
    DiffAlgorithm diffAlgorithm = DiffAlgorithm.getAlgorithm(DiffAlgorithm.SupportedAlgorithm.HISTOGRAM);
    fileDiff.editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, fileDiff.a, fileDiff.b);

    // when
    List<Hunk> hunks = fileDiff.getHunks();

    // then
    Hunk expectedHunk = new Hunk();
    expectedHunk.beginA = 0;
    expectedHunk.endA = 3;
    expectedHunk.beginB = 0;
    expectedHunk.endB = 3;
    expectedHunk.lines = new ArrayList<>();
    expectedHunk.lines.add(new DiffLine(fileDiff, DiffLineType.CONTEXT, 0, 0, "apple"));
    expectedHunk.lines.add(new DiffLine(fileDiff, DiffLineType.CONTEXT, 1, 1, "banana"));
    expectedHunk.lines.add(new DiffLine(fileDiff, DiffLineType.REMOVE, 2, null, "cat"));
    expectedHunk.lines.add(new DiffLine(fileDiff, DiffLineType.ADD, null, 2, "corn"));
    ArrayList<Hunk> expectedHunks = new ArrayList<>();
    expectedHunks.add(expectedHunk);
    assertThat(hunks).describedAs("Test FileDiff.hunks").isEqualTo(expectedHunks);
}

From source file:org.sjanisch.skillview.git.GitAlgorithmContentDiff.java

License:Open Source License

private static Collection<String> diff(String previousContent, String currentContent, DiffAlgorithm algorithm) {
    RawText previous = new RawText(previousContent.getBytes());
    RawText current = new RawText(currentContent.getBytes());
    EditList edits = algorithm.diff(RawTextComparator.WS_IGNORE_ALL, previous, current);

    Collection<String> result = new LinkedList<>();
    for (int i = 0; i < edits.size(); ++i) {
        Edit edit = edits.get(i);/*www.ja  v  a 2 s .  com*/

        switch (edit.getType()) {
        case INSERT:
        case REPLACE:
            String touched = current.getString(edit.getBeginB(), edit.getEndB(), false).trim();
            result.add(touched);
            break;
        default:
            continue;
        }

    }

    return result;
}

From source file:playRepository.GitRepository.java

License:Apache License

private static List<FileDiff> getFileDiffs(final Repository repositoryA, Repository repositoryB,
        ObjectId commitA, ObjectId commitB) throws IOException {
    class MultipleRepositoryObjectReader extends ObjectReader {
        Collection<ObjectReader> readers = new HashSet<>();

        @Override// w w w. j  av a 2s  .  c o m
        public ObjectReader newReader() {
            return new MultipleRepositoryObjectReader(readers);
        }

        public MultipleRepositoryObjectReader(Collection<ObjectReader> readers) {
            this.readers = readers;
        }

        public MultipleRepositoryObjectReader() {
            this.readers = new HashSet<>();
        }

        public void addObjectReader(ObjectReader reader) {
            this.readers.add(reader);
        }

        @Override
        public Collection<ObjectId> resolve(AbbreviatedObjectId id) throws IOException {
            Set<ObjectId> result = new HashSet<>();
            for (ObjectReader reader : readers) {
                result.addAll(reader.resolve(id));
            }
            return result;
        }

        @Override
        public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException {
            for (ObjectReader reader : readers) {
                if (reader.has(objectId, typeHint)) {
                    return reader.open(objectId, typeHint);
                }
            }
            return null;
        }

        @Override
        public Set<ObjectId> getShallowCommits() throws IOException {
            Set<ObjectId> union = new HashSet<>();
            for (ObjectReader reader : readers) {
                union.addAll(reader.getShallowCommits());
            }
            return union;
        }
    }

    final MultipleRepositoryObjectReader reader = new MultipleRepositoryObjectReader();
    reader.addObjectReader(repositoryA.newObjectReader());
    reader.addObjectReader(repositoryB.newObjectReader());

    @SuppressWarnings("rawtypes")
    Repository fakeRepo = new Repository(new BaseRepositoryBuilder()) {

        @Override
        public void create(boolean bare) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ObjectDatabase getObjectDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public RefDatabase getRefDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public StoredConfig getConfig() {
            return repositoryA.getConfig();
        }

        @Override
        public void scanForRepoChanges() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void notifyIndexChanged() {
            throw new UnsupportedOperationException();
        }

        @Override
        public ReflogReader getReflogReader(String refName) throws IOException {
            throw new UnsupportedOperationException();
        }

        public ObjectReader newObjectReader() {
            return reader;
        }
    };

    DiffFormatter formatter = new DiffFormatter(NullOutputStream.INSTANCE);
    formatter.setRepository(fakeRepo);
    formatter.setDetectRenames(true);

    AbstractTreeIterator treeParserA, treeParserB;
    RevTree treeA = null, treeB = null;

    if (commitA != null) {
        treeA = new RevWalk(repositoryA).parseTree(commitA);
        treeParserA = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserA).reset(reader, treeA);
    } else {
        treeParserA = new EmptyTreeIterator();
    }

    if (commitB != null) {
        treeB = new RevWalk(repositoryB).parseTree(commitB);
        treeParserB = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserB).reset(reader, treeB);
    } else {
        treeParserB = new EmptyTreeIterator();
    }

    List<FileDiff> result = new ArrayList<>();
    int size = 0;
    int lines = 0;

    for (DiffEntry diff : formatter.scan(treeParserA, treeParserB)) {
        FileDiff fileDiff = new FileDiff();
        fileDiff.commitA = commitA != null ? commitA.getName() : null;
        fileDiff.commitB = commitB != null ? commitB.getName() : null;

        fileDiff.changeType = diff.getChangeType();

        fileDiff.oldMode = diff.getOldMode();
        fileDiff.newMode = diff.getNewMode();

        String pathA = diff.getPath(DiffEntry.Side.OLD);
        String pathB = diff.getPath(DiffEntry.Side.NEW);

        byte[] rawA = null;
        if (treeA != null && Arrays.asList(DELETE, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t1 = TreeWalk.forPath(repositoryA, pathA, treeA);
            ObjectId blobA = t1.getObjectId(0);
            fileDiff.pathA = pathA;

            try {
                rawA = repositoryA.open(blobA).getBytes();
                fileDiff.isBinaryA = RawText.isBinary(rawA);
                fileDiff.a = fileDiff.isBinaryA ? null : new RawText(rawA);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.A_SIZE_EXCEEDED);
            }
        }

        byte[] rawB = null;
        if (treeB != null && Arrays.asList(ADD, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t2 = TreeWalk.forPath(repositoryB, pathB, treeB);
            ObjectId blobB = t2.getObjectId(0);
            fileDiff.pathB = pathB;

            try {
                rawB = repositoryB.open(blobB).getBytes();
                fileDiff.isBinaryB = RawText.isBinary(rawB);
                fileDiff.b = fileDiff.isBinaryB ? null : new RawText(rawB);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.B_SIZE_EXCEEDED);
            }
        }

        if (size > DIFF_SIZE_LIMIT || lines > DIFF_LINE_LIMIT) {
            fileDiff.addError(FileDiff.Error.OTHERS_SIZE_EXCEEDED);
            result.add(fileDiff);
            continue;
        }

        // Get diff if necessary
        if (fileDiff.a != null && fileDiff.b != null && !(fileDiff.isBinaryA || fileDiff.isBinaryB)
                && Arrays.asList(MODIFY, RENAME).contains(diff.getChangeType())) {
            DiffAlgorithm diffAlgorithm = DiffAlgorithm
                    .getAlgorithm(repositoryB.getConfig().getEnum(ConfigConstants.CONFIG_DIFF_SECTION, null,
                            ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
            fileDiff.editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, fileDiff.a, fileDiff.b);
            size += fileDiff.getHunks().size;
            lines += fileDiff.getHunks().lines;
        }

        // update lines and sizes
        if (fileDiff.b != null && !fileDiff.isBinaryB && diff.getChangeType().equals(ADD)) {
            lines += fileDiff.b.size();
            size += rawB.length;
        }

        // update lines and sizes
        if (fileDiff.a != null && !fileDiff.isBinaryA && diff.getChangeType().equals(DELETE)) {
            lines += fileDiff.a.size();
            size += rawA.length;
        }

        // Stop if exceeds the limit for total number of files
        if (result.size() > DIFF_FILE_LIMIT) {
            break;
        }

        result.add(fileDiff);
    }

    return result;
}