Example usage for org.eclipse.jgit.treewalk.filter TreeFilter ANY_DIFF

List of usage examples for org.eclipse.jgit.treewalk.filter TreeFilter ANY_DIFF

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk.filter TreeFilter ANY_DIFF.

Prototype

TreeFilter ANY_DIFF

To view the source code for org.eclipse.jgit.treewalk.filter TreeFilter ANY_DIFF.

Click Source Link

Document

Selects only tree entries which differ between at least 2 trees.

Usage

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

private static TreeFilter getDiffTreeFilterFor(AbstractTreeIterator a, AbstractTreeIterator b) {
    if (a instanceof DirCacheIterator && b instanceof WorkingTreeIterator)
        return new IndexDiffFilter(0, 1);

    if (a instanceof WorkingTreeIterator && b instanceof DirCacheIterator)
        return new IndexDiffFilter(1, 0);

    TreeFilter filter = TreeFilter.ANY_DIFF;
    if (a instanceof WorkingTreeIterator)
        filter = AndTreeFilter.create(new NotIgnoredFilter(0), filter);
    if (b instanceof WorkingTreeIterator)
        filter = AndTreeFilter.create(new NotIgnoredFilter(1), filter);
    return filter;
}

From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java

License:Apache License

private void filterOutOtherModulesChanges(final String modulePath, final List<String> childModules,
        final RevWalk walk) {
    final boolean isRootModule = ".".equals(modulePath);
    final boolean isMultiModuleProject = !isRootModule || !childModules.isEmpty();
    final List<TreeFilter> treeFilters = new LinkedList<>();
    treeFilters.add(TreeFilter.ANY_DIFF);
    if (isMultiModuleProject) {
        if (!isRootModule) {
            // for sub-modules, look for changes only in the sub-module
            // path...
            treeFilters.add(PathFilter.create(modulePath));
        }/*from  w ww.  ja v a  2 s .co m*/

        // ... but ignore any sub-modules of the current sub-module, because
        // they can change independently of the current module
        for (final String childModule : childModules) {
            final String path = isRootModule ? childModule : modulePath + "/" + childModule;
            treeFilters.add(PathFilter.create(path).negate());
        }

    }
    final TreeFilter treeFilter = treeFilters.size() == 1 ? treeFilters.get(0)
            : AndTreeFilter.create(treeFilters);
    walk.setTreeFilter(treeFilter);
}

From source file:com.gitblit.utils.IssueUtils.java

License:Apache License

/**
 * Returns all the issues in the repository. Querying issues from the
 * repository requires deserializing all changes for all issues. This is an
 * expensive process and not recommended. Issues should be indexed by Lucene
 * and queries should be executed against that index.
 * //from w w w.  j  a v  a  2s  .  co m
 * @param repository
 * @param filter
 *            optional issue filter to only return matching results
 * @return a list of issues
 */
public static List<IssueModel> getIssues(Repository repository, IssueFilter filter) {
    List<IssueModel> list = new ArrayList<IssueModel>();
    RefModel issuesBranch = getIssuesBranch(repository);
    if (issuesBranch == null) {
        return list;
    }

    // Collect the set of all issue paths
    Set<String> issuePaths = new HashSet<String>();
    final TreeWalk tw = new TreeWalk(repository);
    try {
        RevCommit head = JGitUtils.getCommit(repository, GB_ISSUES);
        tw.addTree(head.getTree());
        tw.setRecursive(false);
        while (tw.next()) {
            if (tw.getDepth() < 2 && tw.isSubtree()) {
                tw.enterSubtree();
                if (tw.getDepth() == 2) {
                    issuePaths.add(tw.getPathString());
                }
            }
        }
    } catch (IOException e) {
        error(e, repository, "{0} failed to query issues");
    } finally {
        tw.release();
    }

    // Build each issue and optionally filter out unwanted issues

    for (String issuePath : issuePaths) {
        RevWalk rw = new RevWalk(repository);
        try {
            RevCommit start = rw.parseCommit(repository.resolve(GB_ISSUES));
            rw.markStart(start);
        } catch (Exception e) {
            error(e, repository, "Failed to find {1} in {0}", GB_ISSUES);
        }
        TreeFilter treeFilter = AndTreeFilter.create(PathFilterGroup.createFromStrings(issuePath),
                TreeFilter.ANY_DIFF);
        rw.setTreeFilter(treeFilter);
        Iterator<RevCommit> revlog = rw.iterator();

        List<RevCommit> commits = new ArrayList<RevCommit>();
        while (revlog.hasNext()) {
            commits.add(revlog.next());
        }

        // release the revwalk
        rw.release();

        if (commits.size() == 0) {
            LOGGER.warn("Failed to find changes for issue " + issuePath);
            continue;
        }

        // sort by commit order, first commit first
        Collections.reverse(commits);

        StringBuilder sb = new StringBuilder("[");
        boolean first = true;
        for (RevCommit commit : commits) {
            if (!first) {
                sb.append(',');
            }
            String message = commit.getFullMessage();
            // commit message is formatted: C ISSUEID\n\nJSON
            // C is an single char commit code
            // ISSUEID is an SHA-1 hash
            String json = message.substring(43);
            sb.append(json);
            first = false;
        }
        sb.append(']');

        // Deserialize the JSON array as a Collection<Change>, this seems
        // slightly faster than deserializing each change by itself.
        Collection<Change> changes = JsonUtils.fromJsonString(sb.toString(),
                new TypeToken<Collection<Change>>() {
                }.getType());

        // create an issue object form the changes
        IssueModel issue = buildIssue(changes, true);

        // add the issue, conditionally, to the list
        if (filter == null) {
            list.add(issue);
        } else {
            if (filter.accept(issue)) {
                list.add(issue);
            }
        }
    }

    // sort the issues by creation
    Collections.sort(list);
    return list;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns a list of commits for the repository or a path within the
 * repository. Caller may specify ending revision with objectId. Caller may
 * specify offset and maxCount to achieve pagination of results. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository//from   w  w  w.  j a  v  a  2  s . com
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param path
 *            if unspecified, commits for repository are returned. If
 *            specified, commits for the path are returned.
 * @param offset
 * @param maxCount
 *            if < 0, all commits are returned.
 * @return a paged list of commits
 */
public static List<RevCommit> getRevLog(Repository repository, String objectId, String path, int offset,
        int maxCount) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (maxCount == 0) {
        return list;
    }
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        // resolve branch
        ObjectId startRange = null;
        ObjectId endRange;
        if (StringUtils.isEmpty(objectId)) {
            endRange = getDefaultBranch(repository);
        } else {
            if (objectId.contains("..")) {
                // range expression
                String[] parts = objectId.split("\\.\\.");
                startRange = repository.resolve(parts[0]);
                endRange = repository.resolve(parts[1]);
            } else {
                // objectid
                endRange = repository.resolve(objectId);
            }
        }
        if (endRange == null) {
            return list;
        }

        RevWalk rw = new RevWalk(repository);
        rw.markStart(rw.parseCommit(endRange));
        if (startRange != null) {
            rw.markUninteresting(rw.parseCommit(startRange));
        }
        if (!StringUtils.isEmpty(path)) {
            TreeFilter filter = AndTreeFilter.create(
                    PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
            rw.setTreeFilter(filter);
        }
        Iterable<RevCommit> revlog = rw;
        if (offset > 0) {
            int count = 0;
            for (RevCommit rev : revlog) {
                count++;
                if (count > offset) {
                    list.add(rev);
                    if (maxCount > 0 && list.size() == maxCount) {
                        break;
                    }
                }
            }
        } else {
            for (RevCommit rev : revlog) {
                list.add(rev);
                if (maxCount > 0 && list.size() == maxCount) {
                    break;
                }
            }
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path);
    }
    return list;
}

From source file:com.google.gitiles.blame.BlameCacheImpl.java

License:Open Source License

@Override
public ObjectId findLastCommit(Repository repo, ObjectId commitId, String path) throws IOException {
    // Default implementation does no caching.
    RevWalk rw = new RevWalk(repo);
    try {//from w w w. j av a2s.  c  o  m
        rw.markStart(rw.parseCommit(commitId));
        rw.setRewriteParents(false);
        // Don't use rename detection, even though BlameGenerator does. It is not
        // possible for a commit to modify a path when not doing rename detection
        // but to not modify the same path when taking renames into account.
        rw.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(path), TreeFilter.ANY_DIFF));
        return rw.next();
    } finally {
        rw.release();
    }
}

From source file:com.googlesource.gerrit.plugins.findowners.OwnersValidator.java

License:Apache License

/**
 * Find all TreeWalk entries which differ between the commit and its parents. If a TreeWalk entry
 * is found this method calls the onVisit() method of the class TreeWalkVisitor.
 *//*  w  w w .  j  a v  a 2  s  . c  om*/
private static void visitChangedEntries(RevCommit c, RevWalk revWalk, TreeWalkVisitor visitor)
        throws IOException {
    try (TreeWalk tw = new TreeWalk(revWalk.getObjectReader())) {
        tw.setRecursive(true);
        tw.setFilter(TreeFilter.ANY_DIFF);
        tw.addTree(c.getTree());
        if (c.getParentCount() > 0) {
            for (RevCommit p : c.getParents()) {
                if (p.getTree() == null) {
                    revWalk.parseHeaders(p);
                }
                tw.addTree(p.getTree());
            }
            while (tw.next()) {
                if (isDifferentToAllParents(c, tw)) {
                    visitor.onVisit(tw);
                }
            }
        } else {
            while (tw.next()) {
                visitor.onVisit(tw);
            }
        }
    }
}

From source file:com.googlesource.gerrit.plugins.testplugin.OvirtPatchSetListener.java

License:Apache License

public static Set<String> filesOfCommit(Supplier<Repository> repoSupplier,
        Function<Repository, RevTree> treeSupplier) {
    Set<String> files = new HashSet<>();

    try (Repository repository = repoSupplier.get(); TreeWalk treeWalk = new TreeWalk(repository)) {

        treeWalk.addTree(treeSupplier.apply(repository));
        treeWalk.setRecursive(true);/*from   w w  w  . j av  a 2 s . co  m*/
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        while (treeWalk.next()) {
            if (treeWalk.getPathString().startsWith(FOLDER_PREFIX)) {
                files.add(treeWalk.getNameString());
            }
        }

    } catch (Exception e) {
        log.error("Failed to get files of a commit {} ", treeSupplier, e);
    }
    return files;
}

From source file:com.googlesource.gerrit.plugins.uploadvalidator.CommitUtils.java

License:Apache License

/**
 * This method spots all TreeWalk entries which differ between the passed commit and its parents.
 * If a TreeWalk entry is found this method calls the onVisit() method of the class
 * TreeWalkVisitor./*  w  w w.  ja  va2 s  .  c  o m*/
 *
 * @param repo The repository
 * @param c The commit
 * @param visitor A TreeWalkVisitor with the desired action
 * @throws IOException
 */
public static void visitChangedEntries(Repository repo, RevCommit c, RevWalk revWalk, TreeWalkVisitor visitor)
        throws IOException {
    try (TreeWalk tw = new TreeWalk(revWalk.getObjectReader())) {
        tw.setRecursive(true);
        tw.setFilter(TreeFilter.ANY_DIFF);
        tw.addTree(c.getTree());
        if (c.getParentCount() > 0) {
            for (RevCommit p : c.getParents()) {
                if (p.getTree() == null) {
                    revWalk.parseHeaders(p);
                }
                tw.addTree(p.getTree());
            }
            while (tw.next()) {
                if (isDifferentToAllParents(c, tw)) {
                    visitor.onVisit(tw);
                }
            }
        } else {
            while (tw.next()) {
                visitor.onVisit(tw);
            }
        }
    }
}

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

/**
 * The resolve conflict way of three way merging
 *
 * @param baseTree/*from  ww w.j a  v a 2 s. co  m*/
 * @param headTree
 * @param mergeTree
 * @param ignoreConflicts
 *          Controls what to do in case a content-merge is done and a
 *          conflict is detected. The default setting for this should be
 *          <code>false</code>. In this case the working tree file is
 *          filled with new content (containing conflict markers) and the
 *          index is filled with multiple stages containing BASE, OURS and
 *          THEIRS content. Having such non-0 stages is the sign to git
 *          tools that there are still conflicts for that path.
 *          <p>
 *          If <code>true</code> is specified the behavior is different.
 *          In case a conflict is detected the working tree file is again
 *          filled with new content (containing conflict markers). But
 *          also stage 0 of the index is filled with that content. No
 *          other stages are filled. Means: there is no conflict on that
 *          path but the new content (including conflict markers) is
 *          stored as successful merge result. This is needed in the
 *          context of {@link RecursiveMerger} where when determining
 *          merge bases we don't want to deal with content-merge
 *          conflicts.
 * @return whether the trees merged cleanly
 * @throws IOException
 * @since 3.5
 */
@Override
protected boolean mergeTrees(AbstractTreeIterator baseTree, RevTree headTree, RevTree mergeTree,
        boolean ignoreConflicts) throws IOException {

    this.builder = this.dircache.builder();
    DirCacheBuildIterator buildIt = new DirCacheBuildIterator(this.builder);

    this.tw = new NameConflictTreeWalk(this.reader);
    this.tw.addTree(baseTree);
    this.tw.addTree(headTree);
    this.tw.addTree(mergeTree);
    this.tw.addTree(buildIt);
    if (this.workingTreeIterator != null) {
        this.tw.addTree(this.workingTreeIterator);
    } else {
        this.tw.setFilter(TreeFilter.ANY_DIFF);
    }

    if (!mergeTreeWalk(this.tw, ignoreConflicts)) {
        return false;
    }

    if (!this.inCore) {
        // No problem found. The only thing left to be done is to
        // checkout all files from "theirs" which have been selected to
        // go into the new index.
        checkout();

        // All content-merges are successfully done. If we can now write the
        // new index we are on quite safe ground. Even if the checkout of
        // files coming from "theirs" fails the user can work around such
        // failures by checking out the index again.
        if (!this.builder.commit()) {
            cleanUp();
            throw new IndexWriteException();
        }
        this.builder = null;

    } else {
        this.builder.finish();
        this.builder = null;
    }

    if (getUnmergedPaths().isEmpty() && !failed()) {
        this.resultTree = this.dircache.writeTree(getObjectInserter());
        return true;
    } else {
        this.resultTree = null;
        return false;
    }
}

From source file:com.microsoft.gittf.core.tasks.FetchTaskTest.java

License:Open Source License

@Test
public void testFetchShallow() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/project"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    final MockVersionControlService mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);/*from  www  . java 2 s .c  om*/

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName", //$NON-NLS-1$
            "ownerName", //$NON-NLS-1$
            "committerDisplayName", //$NON-NLS-1$
            "committerName", //$NON-NLS-1$
            "comment", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    final Repository repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Update some files
    mockVersionControlService.AddFile("$/project/folder/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 4); //$NON-NLS-1$

    MockChangesetProperties changesetProperties2 = new MockChangesetProperties("ownerDisplayName4", //$NON-NLS-1$
            "ownerName4", //$NON-NLS-1$
            "committerDisplayName4", //$NON-NLS-1$
            "committerName4", //$NON-NLS-1$
            "comment4", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties2, 4);

    FetchTask fetchTask = new FetchTask(repository, mockVersionControlService);
    TaskStatus fetchTaskStatus = fetchTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(fetchTaskStatus.isOK());

    // Verify the commit fetched
    Ref fetchHeadRef = repository.getRef(Constants.FETCH_HEAD);
    Ref headRef = repository.getRef(Constants.HEAD);

    assertNotNull(fetchHeadRef);
    assertNotNull(headRef);

    ObjectId fetchHeadCommitID = fetchHeadRef.getObjectId();
    ObjectId headCommitID = headRef.getObjectId();

    RevWalk revWalk = new RevWalk(repository);
    RevCommit fetchedCommit = revWalk.parseCommit(fetchHeadCommitID);
    RevCommit headCommit = revWalk.parseCommit(headCommitID);

    assertEquals(fetchedCommit.getFullMessage(), "comment4"); //$NON-NLS-1$

    PersonIdent ownwer = fetchedCommit.getAuthorIdent();
    assertEquals(ownwer.getEmailAddress(), "ownerName4"); //$NON-NLS-1$
    assertEquals(ownwer.getName(), "ownerDisplayName4"); //$NON-NLS-1$

    PersonIdent committer = fetchedCommit.getCommitterIdent();
    assertEquals(committer.getEmailAddress(), "committerName4"); //$NON-NLS-1$
    assertEquals(committer.getName(), "committerDisplayName4"); //$NON-NLS-1$

    // Verify the file content
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setRecursive(true);

    treeWalk.addTree(headCommit.getTree());
    treeWalk.addTree(fetchedCommit.getTree());

    treeWalk.setFilter(TreeFilter.ANY_DIFF);

    int count = 0;
    while (treeWalk.next()) {
        ObjectId fileObjectId = treeWalk.getObjectId(1);
        byte[] fileContent = repository.getObjectDatabase().open(fileObjectId, OBJ_BLOB).getBytes();

        switch (count) {
        case 0:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 2:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder2/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 1:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent,
                    "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        }

        count++;
    }

    Git git = new Git(repository);

    // Verify the tags
    List<Ref> tags = git.tagList().call();
    assertEquals(2, tags.size());
}