如何使用 JGit 获取存储库中每个文件的更改次数?

How do I use JGit to get the number of times each file in the repository has been changed?

现在我正在使用 git 日志:

try (Git git = new Git(repo)) {
    Iterable<RevCommit> commits = git.log().all().call();
    for (RevCommit commit : commits) {
        System.out.println("LogCommit: " + commit);
        TreeWalk treeWalk = new TreeWalk(repo);
        treeWalk.reset(commit.getTree().getId());
        while( treeWalk.next() ) {
            String filename = treeWalk.getPathString();
            Integer currentCount = 0;
            if(fileChanges.containsKey(filename)) {
                currentCount = fileChanges.get(filename);
            }
            fileChanges.put(filename, new Integer(currentCount + 1));  
        }
        treeWalk.close();
    }           
} 

问题在于它列出了提交中的所有文件,无论它们是否已更改。假设我更改了一个 css 文件,提交 repo 然后 运行 这段代码,整个 repo 中的每个其他文件的更改次数都会增加一次。

编辑:我相信这段代码可以做到:

try (Git git = new Git(repo)) {

            DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
            df.setRepository( git.getRepository() );

            Iterable<RevCommit> commits = git.log().all().call();
            for (RevCommit commit : commits) {
                if(commit.getParents().length != 0) {
                    System.out.println("LogCommit: " + commit);

                    List<DiffEntry> entries = df.scan(commit.getId(), commit.getParent(0).getId());
                    for( DiffEntry entry : entries ) {
                        String filename = entry.getPath(DiffEntry.Side.NEW);

                        if(!filename.equals("/dev/null")) {
                            Integer currentCount = 0;

                            if(fileChanges.containsKey(filename)) {
                                currentCount = fileChanges.get(filename);
                            }else {
                                System.out.println("    DiffEntry: " +entry.getPath(DiffEntry.Side.NEW));
                            }
                            fileChanges.put(filename, new Integer(currentCount + 1));
                        }
                    }
                }
            }
        }

我认为您正在寻找的是所有提交的各自差异。以下 post 应该有助于列出所有提交:

要了解两次提交之间的差异,请查看此处:How to show changes between commits with JGit

为了更深入地讨论 JGit 的差异 API,我前段时间写了一篇文章:http://www.codeaffine.com/2016/06/16/jgit-diff/