List of usage examples for org.eclipse.jgit.treewalk.filter AndTreeFilter create
public static TreeFilter create(TreeFilter a, TreeFilter b)
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 ww w . ja v a 2s. 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: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: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 www . j a va 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/* w ww .ja va 2s. c o m*/ * @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 a 2 s . co 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.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./*from w ww. j a v a 2 s . c o m*/ * <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);//from w ww . j a va 2 s . co 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.fau.osr.core.vcs.impl.GitVcsClient.java
License:Open Source License
public Iterator<String> getCommitListForFileodification(String path) { String filename = path.replaceAll(Matcher.quoteReplacement("\\"), "/"); PlotCommitList<PlotLane> plotCommitList = new PlotCommitList<PlotLane>(); PlotWalk revWalk = new PlotWalk(repo); ArrayList<String> commitIDList = new ArrayList<String>(); try {// www.j a v a2s . co m ObjectId rootId = repo.resolve("HEAD"); if (rootId != null) { RevCommit root = revWalk.parseCommit(rootId); revWalk.markStart(root); revWalk.setTreeFilter( // VERY IMPORTANT: This works only with unix-style file paths. NO "\" allowed. AndTreeFilter.create(PathFilter.create(filename), TreeFilter.ANY_DIFF)); plotCommitList.source(revWalk); plotCommitList.fillTo(Integer.MAX_VALUE); Iterator<PlotCommit<PlotLane>> commitListIterator = plotCommitList.iterator(); while (commitListIterator.hasNext()) { commitIDList.add(commitListIterator.next().getName()); } return commitIDList.iterator(); } } catch (AmbiguousObjectException ex) { } catch (IOException ex) { } return commitIDList.iterator(); }
From source file:de.fkoeberle.autocommit.git.GitRepositoryAdapter.java
License:Open Source License
private void visitHeadIndexDelta(GitFileSetDeltaVisitor... visitors) throws IOException { TreeWalk treeWalk = new TreeWalk(repository); treeWalk.setRecursive(true);/* w w w . j ava 2s . com*/ ObjectId headTreeId = repository.resolve(Constants.HEAD); DirCache dirCache = repository.readDirCache(); DirCacheIterator dirCacheTree = new DirCacheIterator(dirCache); int dirCacheTreeIndex = treeWalk.addTree(dirCacheTree); if (headTreeId == null) { while (treeWalk.next()) { DirCacheIterator dirCacheMatch = treeWalk.getTree(dirCacheTreeIndex, DirCacheIterator.class); final String path = treeWalk.getPathString(); ObjectId newObjectId = dirCacheMatch.getEntryObjectId(); for (GitFileSetDeltaVisitor visitor : visitors) { visitor.visitAddedFile(path, newObjectId); } } } else { RevWalk revWalk = new RevWalk(repository); RevTree revTree = revWalk.parseTree(headTreeId); int revTreeIndex = treeWalk.addTree(revTree); TreeFilter filter = AndTreeFilter.create(TreeFilter.ANY_DIFF, new SkipWorkTreeFilter(dirCacheTreeIndex)); treeWalk.setFilter(filter); while (treeWalk.next()) { AbstractTreeIterator headMatch = treeWalk.getTree(revTreeIndex, AbstractTreeIterator.class); DirCacheIterator dirCacheMatch = treeWalk.getTree(dirCacheTreeIndex, DirCacheIterator.class); final String path = treeWalk.getPathString(); visitDeltaWithAll(path, headMatch, dirCacheMatch, visitors); } } }
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; }//from w w w . j a v a 2 s . c om } return false; }