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

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

Introduction

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

Prototype

public static List<DiffEntry> scan(TreeWalk walk) throws IOException 

Source Link

Document

Convert the TreeWalk into DiffEntry headers.

Usage

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

/**
* Determine the differences between two trees.
*
* No output is created, instead only the file paths that are different are
* returned. Callers may choose to format these paths themselves, or convert
* them into {@link FileHeader} instances with a complete edit list by
*
* @param a/*from w w w . j  ava 2 s . c  o  m*/
*            the old (or previous) side.
* @param b
*            the new (or updated) side.
* @return the paths that are different.
* @throws IOException
*             trees cannot be read or file contents cannot be read.
*/
public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b) throws IOException {
    assertHaveRepository();

    TreeWalk walk = new TreeWalk(reader);
    walk.addTree(a);
    walk.addTree(b);
    walk.setRecursive(true);

    TreeFilter filter = getDiffTreeFilterFor(a, b);
    if (pathFilter instanceof FollowFilter) {
        walk.setFilter(AndTreeFilter.create(PathFilter.create(((FollowFilter) pathFilter).getPath()), filter));
    } else {
        walk.setFilter(AndTreeFilter.create(pathFilter, filter));
    }

    source = new ContentSource.Pair(source(a), source(b));

    List<DiffEntry> files = DiffEntry.scan(walk);
    if (pathFilter instanceof FollowFilter && isAdd(files)) {
        // The file we are following was added here, find where it
        // came from so we can properly show the rename or copy,
        // then continue digging backwards.
        //
        a.reset();
        b.reset();
        walk.reset();
        walk.addTree(a);
        walk.addTree(b);
        walk.setFilter(filter);

        if (renameDetector == null)
            setDetectRenames(true);
        files = updateFollowFilter(detectRenames(DiffEntry.scan(walk)));

    } else if (renameDetector != null)
        files = detectRenames(files);

    return files;
}

From source file:com.microsoft.gittf.core.tasks.pendDiff.PendDifferenceTask.java

License:Open Source License

/**
 * Creates the CheckinAnalysisChangeCollection analysis object that includes
 * the list of pending changes needed that map to the differences between
 * the fromCommit and toCommit/* www. j a  v  a  2s  .c  o m*/
 * 
 * @param repository
 *        the git repository
 * @param fromRootTree
 *        the from commit tree
 * @param toRootTree
 *        the to commit tree
 * @param renameMode
 *        the rename mode to use when generating the analysis
 * @param progressMonitor
 *        the progress monitor to use to report progress
 * @return
 * @throws Exception
 */
public static CheckinAnalysisChangeCollection analyzeDifferences(Repository repository, RevObject fromRootTree,
        RevObject toRootTree, RenameMode renameMode, final TaskProgressMonitor progressMonitor)
        throws Exception {
    Check.notNull(fromRootTree, "fromRootTree"); //$NON-NLS-1$
    Check.notNull(toRootTree, "toRootTree"); //$NON-NLS-1$
    Check.notNull(progressMonitor, "progressMonitor"); //$NON-NLS-1$

    progressMonitor.beginTask(Messages.getString("PendDifferencesTask.AnalyzingCommits"), //$NON-NLS-1$
            TaskProgressMonitor.INDETERMINATE, TaskProgressDisplay.DISPLAY_SUBTASK_DETAIL);

    /* Init the analysis object */
    final CheckinAnalysisChangeCollection analysis = new CheckinAnalysisChangeCollection(repository,
            fromRootTree, toRootTree);

    log.debug("Walking thru the git-repository tree.");

    /* Init the tree walker object */
    final TreeWalk treeWalker = new NameConflictTreeWalk(repository);
    final RenameDetector repositoryRenameDetector = new RenameDetector(repository);

    try {
        treeWalker.setRecursive(true);

        treeWalker.addTree(fromRootTree);
        treeWalker.addTree(toRootTree);

        treeWalker.setFilter(TreeFilter.ANY_DIFF);

        List<DiffEntry> treeDifferences = DiffEntry.scan(treeWalker);

        log.debug("The number of differences found: " + treeDifferences.size());

        /*
         * If we need to detect file renames then use the rename detector to
         * analayze the differences first
         */
        if (renameMode != RenameMode.NONE) {
            repositoryRenameDetector.addAll(treeDifferences);
            treeDifferences = repositoryRenameDetector.compute();
        }

        /*
         * If the rename mode is either none or file only then we do not
         * need to detect folder deletes as well, since deleting empty
         * folders that have items that have been renamed out is not
         * supported in TFS
         */
        if (renameMode != RenameMode.ALL) {
            analysis.setProcessDeletedFolders(false);
        }

        Map<String, DiffEntry> deleteChanges = new HashMap<String, DiffEntry>();
        Map<String, DiffEntry> addChanges = new HashMap<String, DiffEntry>();

        for (DiffEntry change : treeDifferences) {
            switch (change.getChangeType()) {
            case ADD:
                addChanges.put(change.getNewPath().toUpperCase(), change);
                break;

            case DELETE:
                deleteChanges.put(change.getOldPath().toUpperCase(), change);
                break;
            }
        }

        /* Append each change in to the analysis object */
        for (DiffEntry change : treeDifferences) {
            switch (change.getChangeType()) {
            case ADD:
            case COPY:
                if (!isCaseSensitiveRename(change, deleteChanges, addChanges)) {
                    analysis.pendAdd(new AddChange(change.getNewPath(),
                            CommitUtil.resolveAbbreviatedId(repository, change.getNewId())));
                    analysis.pendPropertyIfChanged(new PropertyChange(change.getNewPath(),
                            CommitUtil.resolveAbbreviatedId(repository, change.getNewId()),
                            change.getNewMode()));
                }
                break;

            case DELETE:
                if (isCaseSensitiveRename(change, deleteChanges, addChanges)) {
                    DiffEntry addChange = addChanges.get(change.getOldPath().toUpperCase());

                    analysis.pendRename(new RenameChange(change.getOldPath(), addChange.getNewPath(),
                            CommitUtil.resolveAbbreviatedId(repository, addChange.getNewId()),
                            !change.getOldId().equals(addChange.getNewId())));
                    analysis.pendPropertyIfChanged(new PropertyChange(addChange.getNewPath(),
                            CommitUtil.resolveAbbreviatedId(repository, addChange.getNewId()),
                            change.getOldMode(), addChange.getNewMode()));
                } else {
                    analysis.pendDelete(new DeleteChange(change.getOldPath(), change.getOldMode()));
                }
                break;

            case MODIFY:
                analysis.pendEdit(new EditChange(change.getNewPath(),
                        CommitUtil.resolveAbbreviatedId(repository, change.getNewId())));
                analysis.pendPropertyIfChanged(new PropertyChange(change.getNewPath(),
                        CommitUtil.resolveAbbreviatedId(repository, change.getNewId()), change.getOldMode(),
                        change.getNewMode()));
                break;

            case RENAME:
                analysis.pendRename(new RenameChange(change.getOldPath(), change.getNewPath(),
                        CommitUtil.resolveAbbreviatedId(repository, change.getNewId()),
                        !change.getOldId().equals(change.getNewId())));
                analysis.pendPropertyIfChanged(new PropertyChange(change.getNewPath(),
                        CommitUtil.resolveAbbreviatedId(repository, change.getNewId()), change.getOldMode(),
                        change.getNewMode()));
            }
        }
    } finally {
        if (treeWalker != null) {
            treeWalker.release();
        }

        progressMonitor.endTask();
    }

    log.debug("Walk thru the git-repository tree finished.");

    return analysis;
}

From source file:com.mpdeimos.ct_tests.vcs.GitFileDiff.java

License:Apache License

/**
 * Computer file diffs for specified tree walk and commit
 *
 * @param walk/*from w ww.  ja  v  a2s.  c om*/
 * @param commit
 * @return non-null but possibly empty array of file diffs
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws CorruptObjectException
 * @throws IOException
 */
public static GitFileDiff[] compute(final TreeWalk walk, final RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    final ArrayList<GitFileDiff> r = new ArrayList<GitFileDiff>();

    if (commit.getParentCount() > 0)
        walk.reset(trees(commit));
    else {
        walk.reset();
        walk.addTree(new EmptyTreeIterator());
        walk.addTree(commit.getTree());
    }

    if (walk.getTreeCount() <= 2) {
        List<DiffEntry> entries = DiffEntry.scan(walk);
        for (DiffEntry entry : entries) {
            final GitFileDiff d = new GitFileDiff(commit, entry);
            r.add(d);
        }
    } else { // DiffEntry does not support walks with more than two trees
        final int nTree = walk.getTreeCount();
        final int myTree = nTree - 1;
        while (walk.next()) {
            if (matchAnyParent(walk, myTree))
                continue;

            final GitFileDiffForMerges d = new GitFileDiffForMerges(commit);
            d.path = walk.getPathString();
            int m0 = 0;
            for (int i = 0; i < myTree; i++)
                m0 |= walk.getRawMode(i);
            final int m1 = walk.getRawMode(myTree);
            d.change = ChangeType.MODIFY;
            if (m0 == 0 && m1 != 0)
                d.change = ChangeType.ADD;
            else if (m0 != 0 && m1 == 0)
                d.change = ChangeType.DELETE;
            else if (m0 != m1 && walk.idEqual(0, myTree))
                d.change = ChangeType.MODIFY; // there is no ChangeType.TypeChanged
            d.blobs = new ObjectId[nTree];
            d.modes = new FileMode[nTree];
            for (int i = 0; i < nTree; i++) {
                d.blobs[i] = walk.getObjectId(i);
                d.modes[i] = walk.getFileMode(i);
            }
            r.add(d);
        }

    }

    final GitFileDiff[] tmp = new GitFileDiff[r.size()];
    r.toArray(tmp);
    return tmp;
}

From source file:com.xiplink.jira.git.FileDiff.java

License:Open Source License

static FileDiff[] compute(final TreeWalk walk, final RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    final ArrayList<FileDiff> r = new ArrayList<FileDiff>();

    if (commit.getParentCount() > 0) {
        walk.reset(trees(commit));// ww  w. ja  va  2 s. c om
    } else {
        walk.reset();
        walk.addTree(new EmptyTreeIterator());
        walk.addTree(commit.getTree());
    }

    if (walk.getTreeCount() <= 2) {
        List<DiffEntry> entries = DiffEntry.scan(walk);
        int number = 0;
        for (DiffEntry entry : entries) {
            final FileDiff d = new FileDiff(commit, entry, number);
            r.add(d);
            number++;
        }
    } else { // DiffEntry does not support walks with more than two trees
        final int nTree = walk.getTreeCount();
        final int myTree = nTree - 1;
        while (walk.next()) {
            if (matchAnyParent(walk, myTree)) {
                continue;
            }

            final FileDiffForMerges d = new FileDiffForMerges(commit);
            d.path = walk.getPathString();
            int m0 = 0;
            for (int i = 0; i < myTree; i++) {
                m0 |= walk.getRawMode(i);
            }
            final int m1 = walk.getRawMode(myTree);
            d.change = ChangeType.MODIFY;
            if (m0 == 0 && m1 != 0) {
                d.change = ChangeType.ADD;
            } else if (m0 != 0 && m1 == 0) {
                d.change = ChangeType.DELETE;
            } else if (m0 != m1 && walk.idEqual(0, myTree)) {
                d.change = ChangeType.MODIFY; // there is no ChangeType.TypeChanged
            }
            d.blobs = new ObjectId[nTree];
            d.modes = new FileMode[nTree];
            for (int i = 0; i < nTree; i++) {
                d.blobs[i] = walk.getObjectId(i);
                d.modes[i] = walk.getFileMode(i);
            }
            r.add(d);
        }

    }

    final FileDiff[] tmp = new FileDiff[r.size()];
    r.toArray(tmp);
    return tmp;
}

From source file:de.andreasgiemza.jgeagle.repo.rcs.JGit.java

License:Open Source License

/**
 *
 * Based on http://stackoverflow.com/a/11504177/2246865 by OneWorld
 *
 * @param follow/*  w w  w .java  2 s  .co  m*/
 * @param start
 * @param path
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
private String getRenamedPath(boolean follow, RevCommit start, String path)
        throws IOException, GitAPIException {
    if (!follow) {
        return null;
    }

    Iterable<RevCommit> allCommitsLater = git.log().add(start).call();

    for (RevCommit commit : allCommitsLater) {
        TreeWalk tw = new TreeWalk(repository);
        tw.addTree(commit.getTree());
        tw.addTree(start.getTree());
        tw.setRecursive(true);
        RenameDetector rd = new RenameDetector(repository);
        rd.addAll(DiffEntry.scan(tw));
        List<DiffEntry> files = rd.compute();

        for (DiffEntry deffE : files) {
            if ((deffE.getChangeType() == DiffEntry.ChangeType.RENAME
                    || deffE.getChangeType() == DiffEntry.ChangeType.COPY)
                    && deffE.getNewPath().contains(path)) {
                return deffE.getOldPath();
            }
        }
    }

    return null;
}

From source file:jbenchmarker.trace.git.GitExtraction.java

License:Open Source License

Commit parseRepository(String path) throws IOException {
    HashMap<String, String> paths = new HashMap<String, String>();
    HashMapSet<String, Integer> identifiers = new HashMapSet<String, Integer>();
    HashMapSet<String, String> children = new HashMapSet<String, String>();
    int freeId = 2;
    Commit head = null;/*from  w ww .  j av a 2 s .  c o  m*/

    RevWalk revwalk = new RevWalk(repository);
    revwalk.sort(RevSort.TOPO);
    if (path != null) {
        revwalk.setTreeFilter(AndTreeFilter.create(PathFilter.create(path), TreeFilter.ANY_DIFF));
    }
    revwalk.markStart(revwalk.parseCommit(repository.resolve("HEAD")));
    Iterator<RevCommit> it = revwalk.iterator();

    while (it.hasNext()) {
        RevCommit commit = it.next();
        Commit co = new Commit(commit, children.getAll(ObjectId.toString(commit)));
        if (head == null) {
            // Head commit
            co.setId("HEAD");
            head = co;
            if (path != null) {
                paths.put("HEAD", path);
            }
            identifiers.put("HEAD", 1);
        }
        co.setReplica(Collections.min(identifiers.getAll(co.getId())));

        if (GitTrace.DEBUG || commit.getParentCount() > 1) {
            // Merge case -> store state
            List<String> mpaths = new LinkedList<String>();
            List<byte[]> mraws = new LinkedList<byte[]>();
            TreeWalk twalk = walker(commit, path); // paths.get(co.getId()));
            while (twalk.next()) {
                ObjectId id = twalk.getObjectId(0);
                mpaths.add(twalk.getPathString());
                mraws.add(open(twalk.getPathString(), id));
            }
            patchCrud.add(new Patch(co, mpaths, mraws));
        }

        if (commit.getParentCount() > 1) {
            ++nbrMergeBefore;
        }

        if (commit.getParentCount() == 0) {
            // Final case : patch without parent
            List<FileEdition> edits = new LinkedList<FileEdition>();
            TreeWalk walk = walker(commit, path); // paths.get(co.getId()));
            while (walk.next()) {
                ObjectId id = walk.getObjectId(0);
                edits.add(new FileEdition(walk.getPathString(),
                        diff(new byte[0], open(walk.getPathString(), id))));
            }
            patchCrud.add(new Patch(co, edits));
        } else {
            detectRevert(commit);
            // Computes replica identifiers
            Iterator<Integer> itid = identifiers.getAll(co.getId()).iterator();

            for (int p = 0; p < commit.getParentCount(); ++p) {
                RevCommit parent = commit.getParent(p);
                String parentId = ObjectId.toString(parent);
                children.put(parentId, co.getId());

                // compute diff
                if (commit.getParentCount() == 1) {
                    List<FileEdition> edits = new LinkedList<FileEdition>();
                    TreeWalk walk = walker(commit, parent, path); // paths.get(co.getId()));
                    for (DiffEntry entry : DiffEntry.scan(walk)) {
                        edits.add(createDiffResult(entry));
                        if (path != null) {
                            paths.put(parentId, entry.getOldPath());
                        }
                    }
                    patchCrud.add(new Patch(co, parent, edits));
                }

                if (itid.hasNext()) {
                    identifiers.put(parentId, itid.next());
                } else if (!identifiers.containsKey(ObjectId.toString(parent))) {
                    identifiers.put(parentId, freeId);
                    ++freeId;
                }
            }

            int i = 0;
            while (itid.hasNext()) {
                identifiers.put(ObjectId.toString(commit.getParent(i)), itid.next());
                i = (i + 1) % commit.getParentCount();
            }
        }
        commitCrud.add(co);
    }
    return head;
}

From source file:org.eclipse.egit.bc.BeyondCompareRepositoryActionHandler.java

License:Open Source License

protected String getPreviousPath(Repository repository, ObjectReader reader, RevCommit headCommit,
        RevCommit previousCommit, String path) throws IOException {
    TreeWalk walk = new TreeWalk(reader);
    walk.setRecursive(true);//from  w w w .  j a  va 2 s  .  c o  m
    walk.addTree(previousCommit.getTree());
    walk.addTree(headCommit.getTree());

    List<DiffEntry> entries = DiffEntry.scan(walk);
    if (entries.size() < 2)
        return path;

    for (DiffEntry diff : entries)
        if (diff.getChangeType() == ChangeType.MODIFY && path.equals(diff.getNewPath()))
            return path;

    RenameDetector detector = new RenameDetector(repository);
    detector.addAll(entries);
    List<DiffEntry> renames = detector.compute(walk.getObjectReader(), NullProgressMonitor.INSTANCE);
    for (DiffEntry diff : renames)
        if (diff.getChangeType() == ChangeType.RENAME && path.equals(diff.getNewPath()))
            return diff.getOldPath();

    return path;
}

From source file:org.eclipse.egit.ui.internal.history.FileDiff.java

License:Open Source License

static FileDiff[] compute(final TreeWalk walk, final RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    final ArrayList<FileDiff> r = new ArrayList<FileDiff>();

    if (commit.getParentCount() > 0)
        walk.reset(trees(commit));/*  w ww .  jav a 2  s. c o  m*/
    else {
        walk.reset();
        walk.addTree(new EmptyTreeIterator());
        walk.addTree(commit.getTree());
    }

    if (walk.getTreeCount() <= 2) {
        List<DiffEntry> entries = DiffEntry.scan(walk);
        for (DiffEntry entry : entries) {
            final FileDiff d = new FileDiff(commit, entry);
            r.add(d);
        }
    } else { // DiffEntry does not support walks with more than two trees
        final int nTree = walk.getTreeCount();
        final int myTree = nTree - 1;
        while (walk.next()) {
            if (matchAnyParent(walk, myTree))
                continue;

            final FileDiffForMerges d = new FileDiffForMerges(commit);
            d.path = walk.getPathString();
            int m0 = 0;
            for (int i = 0; i < myTree; i++)
                m0 |= walk.getRawMode(i);
            final int m1 = walk.getRawMode(myTree);
            d.change = ChangeType.MODIFY;
            if (m0 == 0 && m1 != 0)
                d.change = ChangeType.ADD;
            else if (m0 != 0 && m1 == 0)
                d.change = ChangeType.DELETE;
            else if (m0 != m1 && walk.idEqual(0, myTree))
                d.change = ChangeType.MODIFY; // there is no ChangeType.TypeChanged
            d.blobs = new ObjectId[nTree];
            d.modes = new FileMode[nTree];
            for (int i = 0; i < nTree; i++) {
                d.blobs[i] = walk.getObjectId(i);
                d.modes[i] = walk.getFileMode(i);
            }
            r.add(d);
        }

    }

    final FileDiff[] tmp = new FileDiff[r.size()];
    r.toArray(tmp);
    return tmp;
}

From source file:org.eclipse.mylyn.internal.git.core.GitConnector.java

License:Open Source License

@Override
public ChangeSet getChangeSet(ScmRepository repository, IFileRevision revision, IProgressMonitor monitor)
        throws CoreException {
    Repository repository2 = ((GitRepository) repository).getRepository();
    RevWalk walk = new RevWalk(repository2);
    try {// w ww  .j  av  a2  s  . c  om
        RevCommit commit;
        commit = walk.parseCommit(ObjectId.fromString(revision.getContentIdentifier()));
        TreeWalk treeWalk = new TreeWalk(repository2);
        for (RevCommit p : commit.getParents()) {
            walk.parseHeaders(p);
            walk.parseBody(p);
            treeWalk.addTree(p.getTree());
            //we can compare with one parent only
            break;
        }
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(true);

        List<DiffEntry> entries = DiffEntry.scan(treeWalk);
        List<Change> changes = new ArrayList<Change>();
        File repoDir = repository2.getWorkTree().getAbsoluteFile();

        //define working area repo URI
        IPath repoWorkAreaPath = new Path(repoDir.getAbsolutePath()).addTrailingSeparator();

        for (DiffEntry d : entries) {
            // FIXME - could not work for renaming
            if (!d.getChangeType().equals(org.eclipse.jgit.diff.DiffEntry.ChangeType.RENAME)
                    && d.getOldId().equals(d.getNewId())) {
                continue;
            }

            //Create old and new artifacts with IResource information if available from the current workspace
            ScmArtifact newArtifact = getArtifact(repository, d, false, repoWorkAreaPath);
            ScmArtifact oldArtifact = getArtifact(repository, d, true, repoWorkAreaPath);

            changes.add(new Change(oldArtifact, newArtifact, mapChangeType(d.getChangeType())));
        }

        return changeSet(commit, repository, changes);

    } catch (Exception e) {
        e.printStackTrace();
        throw new CoreException(new Status(IStatus.ERROR, GitConnector.PLUGIN_ID, e.getMessage()));
    }

}

From source file:org.eclipse.orion.server.git.objects.Commit.java

License:Open Source License

@PropertyDescription(name = GitConstants.KEY_COMMIT_DIFFS)
private JSONArray getDiffs() throws JSONException, URISyntaxException, MissingObjectException,
        IncorrectObjectTypeException, IOException {
    if (revCommit.getParentCount() > 0) {
        JSONArray diffs = new JSONArray();

        final TreeWalk tw = new TreeWalk(db);
        final RevWalk rw = new RevWalk(db);
        RevCommit parent = rw.parseCommit(revCommit.getParent(0));
        tw.reset(parent.getTree(), revCommit.getTree());
        tw.setRecursive(true);/*  w  w  w  . j  a  v a  2s.  co  m*/

        if (filter != null)
            tw.setFilter(filter);
        else
            tw.setFilter(TreeFilter.ANY_DIFF);

        List<DiffEntry> l = DiffEntry.scan(tw);
        for (DiffEntry entr : l) {
            JSONObject diff = new JSONObject();
            diff.put(ProtocolConstants.KEY_TYPE, org.eclipse.orion.server.git.objects.Diff.TYPE);
            diff.put(GitConstants.KEY_COMMIT_DIFF_NEWPATH, entr.getNewPath());
            diff.put(GitConstants.KEY_COMMIT_DIFF_OLDPATH, entr.getOldPath());
            diff.put(GitConstants.KEY_COMMIT_DIFF_CHANGETYPE, entr.getChangeType().toString());

            // add diff location for the commit
            String path = entr.getChangeType() != ChangeType.DELETE ? entr.getNewPath() : entr.getOldPath();
            diff.put(GitConstants.KEY_DIFF,
                    createDiffLocation(revCommit.getName(), revCommit.getParent(0).getName(), path));
            diff.put(ProtocolConstants.KEY_CONTENT_LOCATION, createContentLocation(entr, path));

            diffs.put(diff);
        }
        tw.release();

        return diffs;
    }
    return null;
}