org.eclipse.jgit.treewalk.filter.AndTreeFilter Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.filter.AndTreeFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TreeWalkingDiffDetector.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
private void filterOutOtherModulesChanges(String modulePath, List<String> childModules, RevWalk walk) {
    boolean isRootModule = ".".equals(modulePath);
    boolean isMultiModuleProject = !isRootModule || !childModules.isEmpty();
    List<TreeFilter> treeFilters = new ArrayList<>();
    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));
        }

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

    }
    TreeFilter treeFilter = treeFilters.size() == 1 ? treeFilters.get(0) : AndTreeFilter.create(treeFilters);
    walk.setTreeFilter(treeFilter);
}
 
Example #2
Source File: Git.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 5 votes vote down vote up
/**
  * Get Commit that changed the file before the parameter commit
  * @param sha
  * @param file
  * @return
  */
 public String getPreviousCommit (String sha, String file, PrintWriter l){
  if (sha.equals("a8da84c614ba6e6e87c6c91e0c426ddfec2766a2"))
	  System.out.println();
  File  localRepo1 = new File(workingDirectory+"");
  Iterable<RevCommit> iterable;
  String finalSha = "";
  RevCommit latestCommit = null;
  String path = file;
  try {
	org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.open(localRepo1);
	RevWalk revWalk = new RevWalk( git.getRepository() );
    RevCommit revCommit = getCommit(sha, null);
    revWalk.markStart( revCommit );
    revWalk.sort( RevSort.COMMIT_TIME_DESC );
    revWalk.setTreeFilter( AndTreeFilter.create( PathFilter.create( path ), TreeFilter.ANY_DIFF ) );
    latestCommit = revWalk.next();
    while (!latestCommit.getName().equals(sha))
    	latestCommit = revWalk.next();
    latestCommit = revWalk.next();
    if (latestCommit == null)
    	return null;
    finalSha =  latestCommit.getName();

  } catch (Exception e) {
	 l.println("No Predecessor-Commits found for "+sha +"for file " + file);
	return null;
}
  return finalSha;
 }
 
Example #3
Source File: GitRevisionInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void listFiles() throws GitException {
    try (RevWalk revWalk = new RevWalk(repository);
        TreeWalk walk = new TreeWalk(repository)) {
        List<GitFileInfo> result;
        walk.reset();
        walk.setRecursive(true);
        RevCommit parentCommit = null;
        if (revCommit.getParentCount() > 0) {
            for (RevCommit commit : revCommit.getParents()) {
                revWalk.markStart(revWalk.lookupCommit(commit));
            }
            revWalk.setRevFilter(RevFilter.MERGE_BASE);
            Iterator<RevCommit> it = revWalk.iterator();
            if (it.hasNext()) {
                parentCommit = it.next();
            }
            if (parentCommit != null) {
                walk.addTree(parentCommit.getTree().getId());
            }
        }
        walk.addTree(revCommit.getTree().getId());
        walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        if (parentCommit != null) {
            result = Utils.getDiffEntries(repository, walk, GitClassFactoryImpl.getInstance());
        } else {
            result = new ArrayList<>();
            while (walk.next()) {
                result.add(new GitFileInfo(new File(repository.getWorkTree(), walk.getPathString()), walk.getPathString(), GitFileInfo.Status.ADDED, null, null));
            }
        }
        this.modifiedFiles = result.toArray(new GitFileInfo[result.size()]);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #4
Source File: CompareCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    
    try (TreeWalk walk = new TreeWalk(repository)) {
        walk.reset();
        walk.setRecursive(true);
        walk.addTree(Utils.findCommit(repository, revisionFirst).getTree());
        walk.addTree(Utils.findCommit(repository, revisionSecond).getTree());
        Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
        if (pathFilters.isEmpty()) {
            walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        } else {
            walk.setFilter(AndTreeFilter.create(new TreeFilter[] { 
                TreeFilter.ANY_DIFF,
                PathFilter.ANY_DIFF,
                PathFilterGroup.create(pathFilters)
            }));
        }
        List<GitRevisionInfo.GitFileInfo> infos = Utils.getDiffEntries(repository, walk, getClassFactory());
        for (GitRevisionInfo.GitFileInfo info : infos) {
            statuses.put(info.getFile(), info);
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #5
Source File: ExportCommitCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    String workTreePath = repository.getWorkTree().getAbsolutePath();
    RevCommit commit = Utils.findCommit(repository, revisionStr);
    if (commit.getParentCount() > 1) {
        throw new GitException("Unable to export a merge commit");
    }
    try (DiffFormatter formatter = new DiffFormatter(out)) {
        out.write(Constants.encode(formatCommitInfo(commit)));
        formatter.setRepository(repository);
        List<DiffEntry> diffEntries;
        if (commit.getParentCount() > 0) {
            formatter.setDetectRenames(true);
            diffEntries = formatter.scan(commit.getParent(0), commit);
        } else {
            TreeWalk walk = new TreeWalk(repository);
            walk.reset();
            walk.setRecursive(true);
            walk.addTree(new EmptyTreeIterator());
            walk.addTree(commit.getTree());
            walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
            diffEntries = DiffEntry.scan(walk);
        }
        for (DiffEntry ent : diffEntries) {
            if (monitor.isCanceled()) {
                break;
            }
            listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath());
            formatter.format(ent);
        }
        formatter.flush();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #6
Source File: Commit.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Commit(URI cloneLocation, Repository db, RevCommit revCommit, String pattern) {
	super(cloneLocation, db);
	this.revCommit = revCommit;
	if (revCommit.getParentCount() == 0) {
		this.revCommit = parseCommit(revCommit);
	}
	this.pattern = pattern;
	if (pattern != null && !pattern.isEmpty()) {
		filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(pattern)), TreeFilter.ANY_DIFF);
		isRoot = false;
	}
}
 
Example #7
Source File: LogCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void applyCriteria (RevWalk walk, SearchCriteria criteria,
        final RevFlag partOfResultFlag, DiffConfig diffConfig) {
    File[] files = criteria.getFiles();
    if (files.length > 0) {
        Collection<PathFilter> pathFilters = Utils.getPathFilters(getRepository().getWorkTree(), files);
        if (!pathFilters.isEmpty()) {
            if (criteria.isFollow() && pathFilters.size() == 1) {
                walk.setTreeFilter(FollowFilter.create(pathFilters.iterator().next().getPath(), diffConfig));
            } else {
                walk.setTreeFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilterGroup.create(pathFilters)));
            }
        }
    }
    RevFilter filter;
    if (criteria.isIncludeMerges()) {
        filter = RevFilter.ALL;
    } else {
        filter = RevFilter.NO_MERGES;
    }
    filter = AndRevFilter.create(filter, new CancelRevFilter(monitor));
    filter = AndRevFilter.create(filter, new RevFilter() {

        @Override
        public boolean include (RevWalk walker, RevCommit cmit) {
            return cmit.has(partOfResultFlag);
        }

        @Override
        public RevFilter clone () {
            return this;
        }

        @Override
        public boolean requiresCommitBody () {
            return false;
        }
    });

    String username = criteria.getUsername();
    if (username != null && !(username = username.trim()).isEmpty()) {
        filter = AndRevFilter.create(filter, OrRevFilter.create(CommitterRevFilter.create(username), AuthorRevFilter.create(username)));
    }
    String message = criteria.getMessage();
    if (message != null && !(message = message.trim()).isEmpty()) {
        filter = AndRevFilter.create(filter, MessageRevFilter.create(message));
    }
    Date from  = criteria.getFrom();
    Date to  = criteria.getTo();
    if (from != null && to != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.between(from, to));
    } else if (from != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.after(from));
    } else if (to != null) {
        filter = AndRevFilter.create(filter, CommitTimeRevFilter.before(to));
    }
    // this must be at the end, limit filter must apply as the last
    if (criteria.getLimit() != -1) {
        filter = AndRevFilter.create(filter, MaxCountRevFilter.create(criteria.getLimit()));
    }
    walk.setRevFilter(filter);
}
 
Example #8
Source File: LogCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
 * {@link #not(AnyObjectId)}, ..) of this class. Each instance of this class should only be used for one invocation of the command. Don't call this method
 * twice on an instance.
 *
 * @return an iteration over RevCommits
 * @throws NoHeadException
 *             of the references ref cannot be resolved
 */
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
	checkCallable();
	ArrayList<RevFilter> filters = new ArrayList<RevFilter>();

	if (pathFilters.size() > 0)
		walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));

	if (msgFilter != null)
		filters.add(msgFilter);
	if (authorFilter != null)
		filters.add(authorFilter);
	if (committerFilter != null)
		filters.add(committerFilter);
	if (sha1Filter != null)
		filters.add(sha1Filter);
	if (dateFilter != null)
		filters.add(dateFilter);
	if (skip > -1)
		filters.add(SkipRevFilter.create(skip));
	if (maxCount > -1)
		filters.add(MaxCountRevFilter.create(maxCount));
	RevFilter filter = null;
	if (filters.size() > 1) {
		filter = AndRevFilter.create(filters);
	} else if (filters.size() == 1) {
		filter = filters.get(0);
	}

	if (filter != null)
		walk.setRevFilter(filter);

	if (!startSpecified) {
		try {
			ObjectId headId = repo.resolve(Constants.HEAD);
			if (headId == null)
				throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
			add(headId);
		} catch (IOException e) {
			// all exceptions thrown by add() shouldn't occur and represent
			// severe low-level exception which are therefore wrapped
			throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
		}
	}
	setCallable(false);
	return walk;
}
 
Example #9
Source File: CommitUtils.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static List<RevCommit> getFileRevisions(String path, AnyObjectId start, int skip, int limit, ObjectReader reader) throws IOException {
  path = normalizeNodePath(path);
  TreeFilter filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(path), ANY_DIFF);
  return getHistory(start, skip, limit, filter, reader);
}
 
Example #10
Source File: CommitUtils.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static List<RevCommit> getFileRevisions(String path, AnyObjectId start, int skip, int limit, ObjectReader reader) throws IOException {
  path = normalizeNodePath(path);
  TreeFilter filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(path), ANY_DIFF);
  return getHistory(start, skip, limit, filter, reader);
}
 
Example #11
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
public TestVersionResult determineVersions(final String fetchRevision) throws StoreException.ReadException {
    try {
        final RevWalk walk = new RevWalk(git.getRepository());
        final ObjectId commitId = ObjectId.fromString(fetchRevision);
        final RevCommit headTree = walk.parseCommit(commitId);
        final RevTree tree = headTree.getTree();

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        final TreeWalk treeWalk = new TreeWalk(git.getRepository());
        treeWalk.addTree(tree);
        treeWalk.setFilter(AndTreeFilter
            .create(PathFilter.create(testDefinitionsDirectory), PathSuffixFilter.create("definition.json")));
        treeWalk.setRecursive(true);

        final List<TestVersionResult.Test> tests = Lists.newArrayList();
        while (treeWalk.next()) {
            final ObjectId id = treeWalk.getObjectId(0);
            // final RevTree revTree = walk.lookupTree(id);

            final String path = treeWalk.getPathString();
            final String[] pieces = path.split("/");
            final String testname = pieces[pieces.length - 2]; // tree / parent directory name

            // testname, blobid pair
            // note this is the blobid hash - not a commit hash
            // RevTree.id and RevBlob.id
            tests.add(new TestVersionResult.Test(testname, id.name()));
        }

        walk.dispose();
        return new TestVersionResult(
                tests,
                new Date(Long.valueOf(headTree.getCommitTime()) * 1000 /* convert seconds to milliseconds */),
                determineAuthorId(headTree),
                headTree.toObjectId().getName(),
                headTree.getFullMessage()
        );
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}