Example usage for org.eclipse.jgit.revwalk RevWalk setTreeFilter

List of usage examples for org.eclipse.jgit.revwalk RevWalk setTreeFilter

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk RevWalk setTreeFilter.

Prototype

public void setTreeFilter(TreeFilter newFilter) 

Source Link

Document

Set the tree filter used to simplify commits by modified paths.

Usage

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));
        }//  w  w w  .j  a v a2  s .com

        // ... 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  ww w. j a  va2 s. c  om
 * @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  a2 s  .  c  om*/
 * @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 {/*ww w.  j  a va2 s.c om*/
        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.google.gitiles.LogServlet.java

License:Open Source License

private static RevWalk newWalk(Repository repo, GitilesView view)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {
    RevWalk walk = new RevWalk(repo);
    walk.markStart(walk.parseCommit(view.getRevision().getId()));
    if (view.getOldRevision() != Revision.NULL) {
        walk.markUninteresting(walk.parseCommit(view.getOldRevision().getId()));
    }//from w w  w .ja  v  a  2s.c  o  m
    if (!Strings.isNullOrEmpty(view.getTreePath())) {
        walk.setTreeFilter(FollowFilter.create(view.getTreePath()));
    }
    return walk;
}

From source file:com.mycila.maven.plugin.license.git.GitLookup.java

License:Apache License

/**
 * Returns the year of the last change of the given {@code file} based on the history of the present git branch. The
 * year is taken either from the committer date or from the author identity depending on how {@link #dateSource} was
 * initialized./*w w w .  j  ava2s .  c  om*/
 * <p>
 * See also the note on time zones in {@link #GitLookup(File, DateSource, TimeZone, int)}.
 *
 * @param file
 * @return
 * @throws NoHeadException
 * @throws GitAPIException
 * @throws IOException
 */
public int getYearOfLastChange(File file) throws NoHeadException, GitAPIException, IOException {
    String repoRelativePath = pathResolver.relativize(file);

    Status status = new Git(repository).status().addPath(repoRelativePath).call();
    if (!status.isClean()) {
        /* Return the current year for modified and unstaged files */
        return toYear(System.currentTimeMillis(), timeZone != null ? timeZone : DEFAULT_ZONE);
    }

    RevWalk walk = new RevWalk(repository);
    walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD)));
    walk.setTreeFilter(AndTreeFilter.create(PathFilter.create(repoRelativePath), TreeFilter.ANY_DIFF));
    walk.setRevFilter(MaxCountRevFilter.create(checkCommitsCount));
    walk.setRetainBody(false);

    int commitYear = 0;
    for (RevCommit commit : walk) {
        int y;
        switch (dateSource) {
        case COMMITER:
            int epochSeconds = commit.getCommitTime();
            y = toYear(epochSeconds * 1000L, timeZone);
            break;
        case AUTHOR:
            PersonIdent id = commit.getAuthorIdent();
            Date date = id.getWhen();
            y = toYear(date.getTime(), id.getTimeZone());
            break;
        default:
            throw new IllegalStateException("Unexpected " + DateSource.class.getName() + " " + dateSource);
        }
        if (y > commitYear) {
            commitYear = y;
        }
    }
    walk.dispose();
    return commitYear;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static List<Commit> getLog(Repository r, String revision, String path, Region region)
        throws IOException {
    if (path.startsWith("/")) {
        path = path.substring(1);//  w w  w.  j  a  va  2  s .c o m
    }

    List<Commit> commits = new ArrayList<Commit>();

    ObjectId revId = r.resolve(revision);
    RevWalk walk = new RevWalk(r);

    walk.markStart(walk.parseCommit(revId));

    if (path != null && path.trim().length() != 0) {
        walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(path), TreeFilter.ANY_DIFF));
    }

    if (region != null) {
        // if (region.getOffset() > 0 && region.getSize() > 0)
        // walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(region.getOffset()),
        // MaxCountRevFilter.create(region.getSize())));
        /* else */if (region.getOffset() > 0) {
            walk.setRevFilter(SkipRevFilter.create(region.getOffset()));
        }
        // else if (region.getSize() > 0) {
        // walk.setRevFilter(MaxCountRevFilter.create(region.getSize()));
        // }
    }

    int max = region != null && region.getSize() > 0 ? region.getSize() : -1;

    for (RevCommit revCommit : walk) {
        Commit commit = GitDomain.createCommit(revCommit);
        commit.setRepository(r.getDirectory().getName());
        commits.add(commit);
        if (max != -1) {
            if (max == 0) {
                break;
            }
            max--;
        }
    }

    return commits;
}

From source file:de.codesourcery.gittimelapse.GitHelper.java

License:Apache License

protected void visitCommits(File localPath, boolean retainCommitBody, ObjectId startCommit, ICommitVisitor func)
        throws RevisionSyntaxException, AmbiguousObjectException, IncorrectObjectTypeException, IOException {
    if (startCommit == null) {
        throw new RuntimeException("startCommit must not be NULL");
    }//w  w w . ja v  a2  s.c o  m

    final RevWalk walk = new RevWalk(repository);
    try {
        final String path = stripRepoBaseDir(localPath);
        final PathFilter filter = createPathFilter(path);
        TreeFilter group = PathFilterGroup.create(Collections.singleton(filter));

        walk.setTreeFilter(group);
        walk.setRevFilter(new RevFilter() {

            @Override
            public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException,
                    MissingObjectException, IncorrectObjectTypeException, IOException {
                return commitChangesFile(path, filter, cmit);
            }

            @Override
            public RevFilter clone() {
                return this;
            }
        });
        walk.setRetainBody(retainCommitBody);

        final RevCommit startingCommit = walk.parseCommit(startCommit);
        walk.markStart(startingCommit);
        visitCommits(walk, func);
    } finally {
        walk.dispose();
    }
}

From source file:GitBackend.GitAPI.java

License:Apache License

private void getCommitByExactDate(Repository repo, Date execDate, String path) {
    RevWalk walk = new RevWalk(repo);
    try {/*from   w w w  . j  av  a 2  s .co m*/
        walk.markStart(walk.parseCommit(repo.resolve(Constants.HEAD)));

        walk.sort(RevSort.COMMIT_TIME_DESC);
        walk.setTreeFilter(PathFilter.create(path));

        for (RevCommit commit : walk) {
            if (commit.getCommitterIdent().getWhen().equals(execDate)) {
                // this is the commit you are looking for
                walk.parseCommit(commit);
                System.out.println("Commit found: " + commit.getName());
                break;
            }
        }
        walk.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:jbenchmarker.GitMain.java

License:Open Source License

private boolean gotMerge(String gitdir, String path) throws IOException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repo = builder.setGitDir(new File(gitdir + "/.git")).readEnvironment().findGitDir().build();
    RevWalk revwalk = new RevWalk(repo);
    revwalk.setTreeFilter(AndTreeFilter.create(PathFilter.create(path), TreeFilter.ANY_DIFF));
    revwalk.markStart(revwalk.parseCommit(repo.resolve("HEAD")));
    Iterator<RevCommit> it = revwalk.iterator();
    while (it.hasNext()) {
        if (it.next().getParentCount() > 1) {
            return true;
        }//www .  j  a v  a 2s .c o m
    }
    return false;
}