Example usage for org.eclipse.jgit.diff DiffEntry getPath

List of usage examples for org.eclipse.jgit.diff DiffEntry getPath

Introduction

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

Prototype

public String getPath(Side side) 

Source Link

Document

Get the path associated with this file.

Usage

From source file:com.gitblit.wicket.pages.ImageDiffHandler.java

License:Apache License

/**
 * Constructs a URL that will fetch the designated resource in the git repository. The returned string will
 * contain the URL fully URL-escaped, but note that it may still contain unescaped ampersands, so the result
 * must still be run through HTML escaping if it is to be used in HTML.
 *
 * @return the URL to the image, if the given {@link DiffEntry} and {@link Side} refers to an image, or {@code null} otherwise.
 *///  w w w.jav a2 s . c  o m
protected String getImageUrl(DiffEntry entry, Side side) {
    String path = entry.getPath(side);
    int i = path.lastIndexOf('.');
    if (i > 0) {
        String extension = path.substring(i + 1);
        for (String ext : imageExtensions) {
            if (ext.equalsIgnoreCase(extension)) {
                String commitId = Side.NEW.equals(side) ? newCommitId : oldCommitId;
                if (commitId != null) {
                    return RawServlet.asLink(page.getContextUrl(), urlencode(repositoryName), commitId,
                            urlencode(path));
                } else {
                    return null;
                }
            }
        }
    }
    return null;
}

From source file:org.eclipse.egit.core.op.CreatePatchOperation.java

License:Open Source License

private IProject getProject(final DiffEntry ent) {
    Side side = ent.getChangeType() == ChangeType.ADD ? Side.NEW : Side.OLD;
    String path = ent.getPath(side);
    return getProject(path);
}

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/*from   w ww  .j av  a2s  .c  om*/
        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;
}

From source file:util.DifferenceComputer.java

License:Apache License

public static List<DiffEntry> getChangedFilesBetweenTwoCommits(String repoPath, ObjectId ancestor,
        ObjectId commit) {//from ww  w.  ja  v  a 2s . co  m
    List<DiffEntry> diffs = null;

    try {
        // The {tree} will return the underlying tree-id instead of the commit-id itself!
        // For a description of what the carets do see e.g. http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde
        // This means we are selecting the parent of the parent of the parent of the parent of current HEAD and
        // take the tree-ish of it

        Git git = Git.open(new File(repoPath));
        Repository repository = git.getRepository();

        //ObjectId oldHead = repository.resolve(repository.findRef(branchToLookInto).getObjectId().getName()+"^^{tree}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String)
        //ObjectId head = repository.resolve(repository.findRef(branchToLookInto).getObjectId().getName()+"^{tree}");

        ObjectId oldHead = repository.resolve(ancestor.getName() + "^{tree}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String)
        ObjectId head = repository.resolve(commit.getName() + "^{tree}");

        System.out.println("Printing diff between tree: " + oldHead + "and" + head);

        // prepare the two iterators to compute the diff between

        ObjectReader reader = repository.newObjectReader();

        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, oldHead);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, head);

        // finally get the list of changed files
        git = new Git(repository);

        diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
        int changedFiles = 0;
        for (DiffEntry diff : diffs) {
            System.out.println("Entry: " + diff);
            System.out.println("getNewPath: " + diff.getNewPath());
            System.out.println("getScore: " + diff.getScore());
            System.out.println("getChangeType: " + diff.getChangeType());
            System.out.println("getNewMode: " + diff.getNewMode());
            System.out.println("getPath: " + diff.getPath(null));
            changedFiles++;
        }
        System.out.println("Changed Files: " + changedFiles);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Done");

    return diffs;
}