如何使用文件路径列出 JGit 中的提交

How to list commits in JGit with filepath

我想在 Java 中列出本地 Git 存储库的提交。所以我使用下面的代码来做到这一点:

Iterable<RevCommit> commits = git.log().all().call();

但我还需要提交并在 git 日志中列出的每个文件的路径。

关于 IncorrectObjectTypeException, you do have the TreeWalk.reset() 抛出该异常是因为,来自 Javadoc:

the given object id does not denote a tree, but instead names some other non-tree type of object. Note that commits are not trees, even if they are sometimes called a "tree-ish".

请参阅 those examples of TreeWalk.reset 了解如何从给定提交访问树。喜欢 rev.getTree().

解决方案对我有用:

ObjectReader or = repository.newObjectReader();
        RevWalk rw = new RevWalk(or);
        TreeWalk tw = new TreeWalk(or);
          tw.setFilter(TreeFilter.ANY_DIFF);
          tw.setRecursive(true);
          ObjectId start = repository.resolve(Constants.HEAD);
          startId = or.abbreviate(start);
          rw.markStart(rw.parseCommit(start));

          for(;;){
          RevCommit c = rw.next();
          if (c == null){
              break;
          }
          if (c.getParentCount() != 1){
              continue;
          }
          RevCommit p = c.getParent(0);
            rw.parseHeaders(p);
            tw.reset(p.getTree(), c.getTree());
            while (tw.next()) {
                System.out.println(tw.getPathString()+" id: "+c.getId());
            }
          }