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

The following examples show how to use org.eclipse.jgit.treewalk.filter.TreeFilter. 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: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Map<String, BlobWrapper> getContentMapByTreeAndFilter(
        Git git, AbstractTreeIterator tree, TreeFilter filter) throws Exception {
    Map<String, BlobWrapper> contentMap = new LinkedHashMap<>();
    try (TreeWalk treeWalk = new TreeWalk(git.getRepository())) {
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        treeWalk.setFilter(filter);
        while (treeWalk.next()) {
            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = git.getRepository().open(objectId);
            BlobWrapper blobWrapper = BlobWrapper.builder()
                    .blobId(objectId)
                    .content(loader.getBytes())
                    .build();
            contentMap.put(treeWalk.getPathString(), blobWrapper);
        }
    }
    return contentMap;
}
 
Example #2
Source File: PullRequestUpdate.java    From onedev with MIT License 6 votes vote down vote up
public Collection<String> getChangedFiles() {
	if (changedFiles == null) {
		changedFiles = new HashSet<>();
		
		Repository repository = getRequest().getWorkProject().getRepository();
		try (	RevWalk revWalk = new RevWalk(repository);
				TreeWalk treeWalk = new TreeWalk(repository)) {
			RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
			RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
			RevCommit comparisonBaseCommit = revWalk.parseCommit(getRequest().getComparisonBase(baseCommit, headCommit));
			treeWalk.addTree(headCommit.getTree());
			treeWalk.addTree(comparisonBaseCommit.getTree());
			treeWalk.setFilter(TreeFilter.ANY_DIFF);
			while (treeWalk.next())
				changedFiles.add(treeWalk.getPathString());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return changedFiles;
}
 
Example #3
Source File: GitUtils.java    From onedev with MIT License 6 votes vote down vote up
public static Collection<String> getChangedFiles(Repository repository, ObjectId oldCommitId, ObjectId newCommitId) {
Collection<String> changedFiles = new HashSet<>();
try (	RevWalk revWalk = new RevWalk(repository);
		TreeWalk treeWalk = new TreeWalk(repository)) {
	treeWalk.setFilter(TreeFilter.ANY_DIFF);
	treeWalk.setRecursive(true);
	RevCommit oldCommit = revWalk.parseCommit(oldCommitId);
	RevCommit newCommit = revWalk.parseCommit(newCommitId);
	treeWalk.addTree(oldCommit.getTree());
	treeWalk.addTree(newCommit.getTree());
	while (treeWalk.next()) {
		changedFiles.add(treeWalk.getPathString());
	}
} catch (IOException e) {
	throw new RuntimeException(e);
}
return changedFiles;
  }
 
Example #4
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 #5
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private List<DiffEntry> blockingCompareTreesUncached(@Nullable RevTree treeA,
                                                     @Nullable RevTree treeB,
                                                     TreeFilter filter) {
    readLock();
    try (DiffFormatter diffFormatter = new DiffFormatter(null)) {
        diffFormatter.setRepository(jGitRepository);
        diffFormatter.setPathFilter(filter);
        return ImmutableList.copyOf(diffFormatter.scan(treeA, treeB));
    } catch (IOException e) {
        throw new StorageException("failed to compare two trees: " + treeA + " vs. " + treeB, e);
    } finally {
        readUnlock();
    }
}
 
Example #6
Source File: StatusCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Map<String, DiffEntry> detectRenames (Repository repository, DirCache cache, ObjectId commitId) {
    List<DiffEntry> entries;
    try(TreeWalk treeWalk = new TreeWalk(repository);) {
        treeWalk.setRecursive(true);
        treeWalk.reset();
        if (commitId != null) {
            treeWalk.addTree(new RevWalk(repository).parseTree(commitId));
        } else {
            treeWalk.addTree(new EmptyTreeIterator());
        }
        // Index
        treeWalk.addTree(new DirCacheIterator(cache));
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        entries = DiffEntry.scan(treeWalk);
        RenameDetector d = new RenameDetector(repository);
        d.addAll(entries);
        entries = d.compute();
    } catch (IOException ex) {
        entries = Collections.<DiffEntry>emptyList();
    }
    Map<String, DiffEntry> renames = new HashMap<>();
    for (DiffEntry e : entries) {
        if (e.getChangeType().equals(DiffEntry.ChangeType.COPY) || e.getChangeType().equals(DiffEntry.ChangeType.RENAME)) {
            renames.put(e.getNewPath(), e);
        }
    }
    return renames;
}
 
Example #7
Source File: StatusCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Collection<TreeFilter> getSubtreeFilters(Collection<PathFilter> filters, String path) {
    List<TreeFilter> subtreeFilters = new LinkedList<>();
    for (PathFilter filter : filters) {
        if (filter.getPath().startsWith(path + "/")) { //NOI18N
            subtreeFilters.add(filter);
        }
    }
    return subtreeFilters;
}
 
Example #8
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 #9
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 #10
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TreeFilter getExcludeExactPathsFilter (File workDir, File[] roots) {
    Collection<String> relativePaths = getRelativePaths(workDir, roots);
    TreeFilter filter = null;
    if (relativePaths.size() > 0) {
        Collection<PathFilter> filters = getPathFilters(relativePaths);
        List<TreeFilter> exactPathFilters = new LinkedList<TreeFilter>();
        for (PathFilter f : filters) {
            exactPathFilters.add(ExactPathFilter.create(f));
        }
        return NotTreeFilter.create(exactPathFilters.size() == 1 ? exactPathFilters.get(0) : OrTreeFilter.create(exactPathFilters));
    }
    return filter;
}
 
Example #11
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static TreeFilter pathPatternFilterOrTreeFilter(@Nullable String pathPattern) {
    if (pathPattern == null) {
        return TreeFilter.ALL;
    }

    final PathPatternFilter pathPatternFilter = PathPatternFilter.of(pathPattern);
    return pathPatternFilter.matchesAll() ? TreeFilter.ALL : pathPatternFilter;
}
 
Example #12
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, BlobWrapper> getIndexedFileContentMap(Git git, Set<String> filePathSet) throws Exception {
    if (filePathSet == null || filePathSet.isEmpty()) {
        return Collections.emptyMap();
    }
    DirCache index = git.getRepository().readDirCache();
    TreeFilter filter = filePathSet.size() > 1
            ? OrTreeFilter.create(filePathSet.stream()
                    .map(PathFilter::create)
                    .collect(Collectors.toList()))
            : PathFilter.create(filePathSet.iterator().next());
    return getContentMapByTreeAndFilter(git, new DirCacheIterator(index), filter);
}
 
Example #13
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 #14
Source File: DifferentFiles.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
private Set<Path> getBranchDiff() throws IOException {
    RevCommit base = getBranchCommit(configuration.baseBranch);
    final TreeWalk treeWalk = new TreeWalk(git.getRepository());
    try {
        treeWalk.addTree(base.getTree());
        treeWalk.addTree(resolveReference(base).getTree());
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        treeWalk.setRecursive(true);
        return getDiff(treeWalk, workTree);
    } finally {
        treeWalk.close();
    }
}
 
Example #15
Source File: CommitUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<RevCommit> getHistory(AnyObjectId start, int skip, int limit, @Nullable TreeFilter filter, ObjectReader reader) throws IOException {
  List<RevCommit> commits;
  try(RevWalk rw = new RevWalk(reader)) {
    rw.markStart(CommitUtils.getCommit(start, reader));
    if(filter != null)
      rw.setTreeFilter(filter);
    commits = toCommitList(rw, skip, limit);
  }
  return commits;
}
 
Example #16
Source File: CommitUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<RevCommit> getHistory(AnyObjectId start, int skip, int limit, @Nullable TreeFilter filter, ObjectReader reader) throws IOException {
  List<RevCommit> commits;
  try(RevWalk rw = new RevWalk(reader)) {
    rw.markStart(CommitUtils.getCommit(start, reader));
    if(filter != null)
      rw.setTreeFilter(filter);
    commits = toCommitList(rw, skip, limit);
  }
  return commits;
}
 
Example #17
Source File: GitBranch.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private Map<String, String> collectRename(@NotNull GitFile oldTree, @NotNull GitFile newTree) throws IOException {
  if (!repository.hasRenameDetection()) {
    return Collections.emptyMap();
  }
  final GitObject<ObjectId> oldTreeId = oldTree.getObjectId();
  final GitObject<ObjectId> newTreeId = newTree.getObjectId();
  if (oldTreeId == null || newTreeId == null || !Objects.equals(oldTreeId.getRepo(), newTreeId.getRepo())) {
    return Collections.emptyMap();
  }
  final TreeWalk tw = new TreeWalk(repository.getGit());
  tw.setRecursive(true);
  tw.setFilter(TreeFilter.ANY_DIFF);
  tw.addTree(oldTreeId.getObject());
  tw.addTree(newTreeId.getObject());

  final RenameDetector rd = new RenameDetector(repository.getGit());
  rd.addAll(DiffEntry.scan(tw));

  final Map<String, String> result = new HashMap<>();
  for (DiffEntry diff : rd.compute(tw.getObjectReader(), null)) {
    if (diff.getScore() >= rd.getRenameScore()) {
      result.put(StringHelper.normalize(diff.getNewPath()), StringHelper.normalize(diff.getOldPath()));
    }
  }
  return result;
}
 
Example #18
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 #19
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, BlobWrapper> getRevFileContentMap(
        Git git, RevCommit commit, Set<String> filePathSet, ObjectReader reader) throws Exception {
    if (filePathSet == null || filePathSet.isEmpty()) {
        return Collections.emptyMap();
    }
    TreeFilter filter = filePathSet.size() > 1
            ? OrTreeFilter.create(filePathSet.stream()
                    .map(PathFilter::create)
                    .collect(Collectors.toList()))
            : PathFilter.create(filePathSet.iterator().next());
     return getContentMapByTreeAndFilter(git, new CanonicalTreeParser(null, reader, commit.getTree()), filter);
}
 
Example #20
Source File: UIGit.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public String diff( String oldCommitId, String newCommitId, String file ) {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  try {
    getDiffCommand( oldCommitId, newCommitId )
      .setOutputStream( out )
      .setPathFilter( file == null ? TreeFilter.ALL : PathFilter.create( file ) )
      .call();
    return out.toString( "UTF-8" );
  } catch ( Exception e ) {
    return e.getMessage();
  }
}
 
Example #21
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 #22
Source File: RevWalk.java    From onedev with MIT License 5 votes vote down vote up
private RevWalk(ObjectReader or, boolean closeReader) {
	reader = or;
	idBuffer = new MutableObjectId();
	objects = new ObjectIdOwnerMap<>();
	roots = new ArrayList<>();
	queue = new DateRevQueue(false);
	pending = new StartGenerator(this);
	sorting = EnumSet.of(RevSort.NONE);
	filter = RevFilter.ALL;
	treeFilter = TreeFilter.ALL;
	this.closeReader = closeReader;
}
 
Example #23
Source File: TreeRevFilter.java    From onedev with MIT License 5 votes vote down vote up
private void updateFollowFilter(ObjectId[] trees, DiffConfig cfg)
		throws MissingObjectException, IncorrectObjectTypeException,
		CorruptObjectException, IOException {
	TreeWalk tw = pathFilter;
	FollowFilter oldFilter = (FollowFilter) tw.getFilter();
	tw.setFilter(TreeFilter.ANY_DIFF);
	tw.reset(trees);

	List<DiffEntry> files = DiffEntry.scan(tw);
	RenameDetector rd = new RenameDetector(tw.getObjectReader(), cfg);
	rd.addAll(files);
	files = rd.compute();

	TreeFilter newFilter = oldFilter;
	for (DiffEntry ent : files) {
		if (isRename(ent) && ent.getNewPath().equals(oldFilter.getPath())) {
			newFilter = FollowFilter.create(ent.getOldPath(), cfg);
			RenameCallback callback = oldFilter.getRenameCallback();
			if (callback != null) {
				callback.renamed(ent);
				// forward the callback to the new follow filter
				((FollowFilter) newFilter).setRenameCallback(callback);
			}
			break;
		}
	}
	tw.setFilter(newFilter);
}
 
Example #24
Source File: ResolveMerger.java    From onedev with MIT License 4 votes vote down vote up
/**
 * The resolve conflict way of three way merging
 *
 * @param baseTree
 *            a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator}
 *            object.
 * @param headTree
 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
 * @param mergeTree
 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
 * @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 org.eclipse.jgit.merge.RecursiveMerger}
 *            where when determining merge bases we don't want to deal with
 *            content-merge conflicts.
 * @return whether the trees merged cleanly
 * @throws java.io.IOException
 * @since 3.5
 */
protected boolean mergeTrees(AbstractTreeIterator baseTree,
		RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
		throws IOException {

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

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

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

	if (!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 (!builder.commit()) {
			cleanUp();
			throw new IndexWriteException();
		}
		builder = null;

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

	if (getUnmergedPaths().isEmpty() && !failed()) {
		resultTree = dircache.writeTree(getObjectInserter());
		return true;
	}
	resultTree = null;
	return false;
}
 
Example #25
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
/**
 * Formats a commit into the raw format.
 *
 * @param commit
 *      Commit to format.
 * @param parent
 *      Optional parent commit to produce the diff against. This only matters
 *      for merge commits, and git-log/git-whatchanged/etc behaves differently with respect to this.
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE",
        justification = "Windows git implementation requires specific line termination")
void format(RevCommit commit, RevCommit parent, PrintWriter pw, Boolean useRawOutput) throws IOException {
    if (parent!=null)
        pw.printf("commit %s (from %s)\n", commit.name(), parent.name());
    else
        pw.printf("commit %s\n", commit.name());

    pw.printf("tree %s\n", commit.getTree().name());
    for (RevCommit p : commit.getParents())
        pw.printf("parent %s\n",p.name());
    FastDateFormat iso = FastDateFormat.getInstance(ISO_8601);
    PersonIdent a = commit.getAuthorIdent();
    pw.printf("author %s <%s> %s\n", a.getName(), a.getEmailAddress(), iso.format(a.getWhen()));
    PersonIdent c = commit.getCommitterIdent();
    pw.printf("committer %s <%s> %s\n", c.getName(), c.getEmailAddress(), iso.format(c.getWhen()));

    // indent commit messages by 4 chars
    String msg = commit.getFullMessage();
    if (msg.endsWith("\n")) msg=msg.substring(0,msg.length()-1);
    msg = msg.replace("\n","\n    ");
    msg="\n    "+msg+"\n";

    pw.println(msg);

    // see man git-diff-tree for the format
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         TreeWalk tw = new TreeWalk(or)) {
    if (parent != null) {
        /* Caller provided a parent commit, use it */
        tw.reset(parent.getTree(), commit.getTree());
    } else {
        if (commit.getParentCount() > 0) {
            /* Caller failed to provide parent, but a parent
             * is available, so use the parent in the walk
             */
            tw.reset(commit.getParent(0).getTree(), commit.getTree());
        } else {
            /* First commit in repo has 0 parent count, but
             * the TreeWalk requires exactly two nodes for its
             * walk.  Use the same node twice to satisfy
             * TreeWalk. See JENKINS-22343 for details.
             */
            tw.reset(commit.getTree(), commit.getTree());
        }
    }
    tw.setRecursive(true);
    tw.setFilter(TreeFilter.ANY_DIFF);

    final RenameDetector rd = new RenameDetector(repo);

    rd.reset();
    rd.addAll(DiffEntry.scan(tw));
    List<DiffEntry> diffs = rd.compute(or, null);
    if (useRawOutput) {
     for (DiffEntry diff : diffs) {
         pw.printf(":%06o %06o %s %s %s\t%s",
                 diff.getOldMode().getBits(),
                 diff.getNewMode().getBits(),
                 diff.getOldId().name(),
                 diff.getNewId().name(),
                 statusOf(diff),
                 diff.getChangeType()==ChangeType.ADD ? diff.getNewPath() : diff.getOldPath());

         if (hasNewPath(diff)) {
             pw.printf(" %s",diff.getNewPath()); // copied to
         }
         pw.println();
         pw.println();
     }
        }
    }
}
 
Example #26
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 #27
Source File: CommitGit.java    From coming with MIT License 4 votes vote down vote up
@Override
public TreeFilter clone() {
	throw new UnsupportedOperationException();
}
 
Example #28
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 #29
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 #30
Source File: RevWalk.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Determine if a commit is reachable from another commit.
 * <p>
 * A commit <code>base</code> is an ancestor of <code>tip</code> if we
 * can find a path of commits that leads from <code>tip</code> and ends at
 * <code>base</code>.
 * <p>
 * This utility function resets the walker, inserts the two supplied
 * commits, and then executes a walk until an answer can be obtained.
 * Currently allocated RevFlags that have been added to RevCommit instances
 * will be retained through the reset.
 *
 * @param base
 *            commit the caller thinks is reachable from <code>tip</code>.
 * @param tip
 *            commit to start iteration from, and which is most likely a
 *            descendant (child) of <code>base</code>.
 * @return true if there is a path directly from <code>tip</code> to
 *         <code>base</code> (and thus <code>base</code> is fully merged
 *         into <code>tip</code>); false otherwise.
 * @throws org.eclipse.jgit.errors.MissingObjectException
 *             one or more of the next commit's parents are not available
 *             from the object database, but were thought to be candidates
 *             for traversal. This usually indicates a broken link.
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 *             one or more of the next commit's parents are not actually
 *             commit objects.
 * @throws java.io.IOException
 *             a pack file or loose object could not be read.
 */
public boolean isMergedInto(RevCommit base, RevCommit tip)
		throws MissingObjectException, IncorrectObjectTypeException,
		IOException {
	final RevFilter oldRF = filter;
	final TreeFilter oldTF = treeFilter;
	try {
		finishDelayedFreeFlags();
		reset(~freeFlags & APP_FLAGS);
		filter = RevFilter.MERGE_BASE;
		treeFilter = TreeFilter.ALL;
		markStart(tip);
		markStart(base);
		RevCommit mergeBase;
		while ((mergeBase = next()) != null) {
			if (References.isSameObject(mergeBase, base)) {
				return true;
			}
		}
		return false;
	} finally {
		filter = oldRF;
		treeFilter = oldTF;
	}
}