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

The following examples show how to use org.eclipse.jgit.treewalk.filter.PathFilterGroup. 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: 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 #2
Source File: CheckoutRevisionCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void mergeConflicts (List<String> conflicts, DirCache cache) throws GitException {
    DirCacheBuilder builder = cache.builder();
    DirCacheBuildIterator dci = new DirCacheBuildIterator(builder);
    ObjectDatabase od = null;
    DiffAlgorithm.SupportedAlgorithm diffAlg = getRepository().getConfig().getEnum(
                    ConfigConstants.CONFIG_DIFF_SECTION, null,
                    ConfigConstants.CONFIG_KEY_ALGORITHM,
                    DiffAlgorithm.SupportedAlgorithm.HISTOGRAM);
    MergeAlgorithm merger = new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
    try (TreeWalk walk = new TreeWalk(getRepository());) {
        od = getRepository().getObjectDatabase();
        walk.addTree(dci);
        walk.setFilter(PathFilterGroup.create(Utils.getPathFilters(conflicts)));
        String lastPath = null;
        DirCacheEntry[] entries = new DirCacheEntry[3];
        walk.setRecursive(true);
        while (walk.next()) {
            DirCacheEntry e = walk.getTree(0, DirCacheIterator.class).getDirCacheEntry();
            String path = e.getPathString();
            if (lastPath != null && !lastPath.equals(path)) {
                resolveEntries(merger, lastPath, entries, od, builder);
            }
            if (e.getStage() == 0) {
                DirCacheIterator c = walk.getTree(0, DirCacheIterator.class);
                builder.add(c.getDirCacheEntry());
            } else {
                entries[e.getStage() - 1] = e;
                lastPath = path;
            }
        }
        resolveEntries(merger, lastPath, entries, od, builder);
        builder.commit();
    } catch (IOException ex) {
        throw new GitException(ex);
    } finally {
        if (od != null) {
            od.close();
        }
    }
}
 
Example #3
Source File: CheckoutIndex.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void checkout() throws IOException, GitException {
    try (ObjectReader od = repository.newObjectReader();
        TreeWalk treeWalk = new TreeWalk(repository);) {
        Collection<String> relativePaths = Utils.getRelativePaths(repository.getWorkTree(), roots);
        if (!relativePaths.isEmpty()) {
            treeWalk.setFilter(PathFilterGroup.createFromStrings(relativePaths));
        }
        treeWalk.setRecursive(true);
        treeWalk.reset();
        treeWalk.addTree(new DirCacheIterator(cache));
        treeWalk.addTree(new FileTreeIterator(repository));
        String lastAddedPath = null;
        while (treeWalk.next() && !monitor.isCanceled()) {
            File path = new File(repository.getWorkTree(), treeWalk.getPathString());
            if (treeWalk.getPathString().equals(lastAddedPath)) {
                // skip conflicts
                continue;
            } else {
                lastAddedPath = treeWalk.getPathString();
            }
            DirCacheIterator dit = treeWalk.getTree(0, DirCacheIterator.class);
            FileTreeIterator fit = treeWalk.getTree(1, FileTreeIterator.class);
            if (dit != null && (recursively || directChild(roots, repository.getWorkTree(), path)) && (fit == null || fit.isModified(dit.getDirCacheEntry(), checkContent, od))) {
                // update entry
                listener.notifyFile(path, treeWalk.getPathString());
                checkoutEntry(repository, path, dit.getDirCacheEntry(), od);
            }
        }
    }
}
 
Example #4
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 #5
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  protected void run() throws GitException {
      Repository repository = getRepository();
      String workTreePath = repository.getWorkTree().getAbsolutePath();
      try (DiffFormatter formatter = new DiffFormatter(out);
          ObjectReader or = repository.newObjectReader()) {
          formatter.setRepository(repository);
          Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
          if (!pathFilters.isEmpty()) {
              formatter.setPathFilter(PathFilterGroup.create(pathFilters));
          }
          if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
              // work-around for autocrlf
              formatter.setDiffComparator(new AutoCRLFComparator());
          }
          AbstractTreeIterator firstTree = getIterator(firstCommit, or);
          AbstractTreeIterator secondTree = getIterator(secondCommit, or);
          List<DiffEntry> diffEntries;
          if (secondTree instanceof WorkingTreeIterator) {
              // remote when fixed in JGit, see ExportDiffTest.testDiffRenameDetectionProblem
              formatter.setDetectRenames(false);
              diffEntries = formatter.scan(firstTree, secondTree);
              formatter.setDetectRenames(true);
              RenameDetector detector = formatter.getRenameDetector();
              detector.reset();
              detector.addAll(diffEntries);
diffEntries = detector.compute(new ContentSource.Pair(ContentSource.create(or), ContentSource.create((WorkingTreeIterator) secondTree)), NullProgressMonitor.INSTANCE);
          } else {
              formatter.setDetectRenames(true);
              diffEntries = formatter.scan(firstTree, secondTree);
          }
          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: 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 #7
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);
    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);
    
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    // when this starts failing, remove the work around
    ObjectInserter inserter = repository.newObjectInserter();
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setFilter(PathFilterGroup.createFromStrings("f"));
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new FileTreeIterator(repository));
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertEquals("f", path);
        WorkingTreeIterator fit = treeWalk.getTree(0, WorkingTreeIterator.class);
        try (InputStream in = fit.openEntryStream()) {
            inserter.insert(Constants.OBJ_BLOB, fit.getEntryLength(), in);
            fail("this should fail, remove the work around");
        } catch (EOFException ex) {
            assertEquals("Input did not match supplied length. 10.000 bytes are missing.", ex.getMessage());
        } finally {
            inserter.close();
        }
        break;
    }
    
    // no err should occur
    write(f, content + "hello");
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    client.add(files, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    client.commit(files, "message", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
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);
}