繁体   English   中英

如何使用 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。 例如,请参见此处: 如何使用 JGit 从 SHA1 ID 字符串获取 RevCommit 或 ObjectId?

为了迭代一棵树,请使用TreeWalk

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

如果您只对某个提交记录的更改感兴趣,请参阅此处:使用 JGit 创建差异或此处: 使用 JGit 与上次提交的文件差异

我从这个链接中给出的代码中编辑了一些。 您可以尝试使用以下代码。

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);
            }
        }
    }
}

您可以尝试:

 git diff --stat --name-only ${hash} ${hash}~1

或者看到更大范围的差异:

 git diff --stat --name-only ${hash1} ${hash2}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM