如何使用 JGit 获取提交的文件列表

How to get the file list for a commit with JGit

我一直在开发基于 Java 的产品,该产品将集成 Git 功能。使用 Git 功能之一,我通过暂存将 10 多个文件添加到 Git 存储库,然后在一次提交中提交它们。

上述过程的逆过程是否可行?即查找作为提交一部分提交的文件列表。

我在 git.log() 命令的帮助下获得了提交,但我不确定如何获取提交的文件列表。

示例代码:

Git git = (...);
Iterable<RevCommit> logs = git.log().call();
for(RevCommit commit : logs) {
    String commitID = commit.getName();
    if(commitID != null && !commitID.isEmpty()) {
    TableItem item = new TableItem(table, SWT.None);
    item.setText(commitID);
    // Here I want to get the file list for the commit object
}
}

每个提交都指向一个 ,它表示构成提交的所有文件。

请注意,这不仅包括在此特定提交中添加、修改或删除的文件,还包括此修订中包含的所有文件。

如果提交表示为RevCommit,树的ID可以这样获取:

ObjectId treeId = commit.getTree().getId();

如果提交ID来自其他来源,则需要先解析它以获取关联的树ID。参见此处,例如:How to obtain the RevCommit or ObjectId from a SHA1 ID string with JGit?

为了遍历树,使用 TreeWalk:

try (TreeWalk treeWalk = new TreeWalk(repository)) {
  treeWalk.reset(treeId);
  while (treeWalk.next()) {
    String path = treeWalk.getPathString();
    // ...
  }
}

如果您只对某个提交记录的更改感兴趣,请参阅此处:Creating Diffs with JGit or here: File diff against the last commit with JGit

我根据 link 中给出的代码进行了一些编辑。 您可以尝试使用以下代码。

public void commitHistory(Git git) throws NoHeadException, GitAPIException, IncorrectObjectTypeException, CorruptObjectException, IOException, UnirestException 
{
    Iterable<RevCommit> logs = git.log().call();
    int k = 0;
    for (RevCommit commit : logs) {
        String commitID = commit.getName();
        if (commitID != null && !commitID.isEmpty())
        {
            LogCommand logs2 = git.log().all();
            Repository repository = logs2.getRepository();
            tw = new TreeWalk(repository);
            tw.setRecursive(true);
            RevCommit commitToCheck = commit;
            tw.addTree(commitToCheck.getTree());
            for (RevCommit parent : commitToCheck.getParents())
            {
                tw.addTree(parent.getTree());
            }
            while (tw.next())
            {
                int similarParents = 0;
                for (int i = 1; i < tw.getTreeCount(); i++)
                    if (tw.getFileMode(i) == tw.getFileMode(0) && tw.getObjectId(0).equals(tw.getObjectId(i)))
                        similarParents++;
                if (similarParents == 0) 
                        System.out.println("File names: " + fileName);
            }
        }
    }
}