如何在JGit中计算插入/删除的行数

时间:2015-02-24 18:57:20

标签: java git jgit

当我们git log --shortstat时,我们会获得插入,删除和更改的行数。类似的东西:

1 file changed, 9 insertions(+), 3 deletions(-)

请帮助我获取插入,删除和更改的行数。

  1. 我正在进行存储库克隆以在本地计算机上获取git项目。这是相同的代码:

    RepoClone repoClone=new RepoClone();
    repoClone.repoCloner();
    repository =         builder.setGitDir(repoClone.repoDir).setMustExist(true).build();
    
  2. 我甚至可以获得TreeWalk

    TreeWalk treeWalk=getCommitsTreeWalk();
    
  3. 我能够检索文件名,每个文件的提交次数,LOC以及处理每个xml / java文件的开发人员数量。

    while (treeWalk.next()) {
      if (treeWalk.getPathString().endsWith(".xml") || treeWalk.getPathString().endsWith(".java")) {
        jsonDataset = new JSONObject();
        countDevelopers = new HashSet < String > ();
        count = 0;
        logs = new Git(repository).log().addPath(treeWalk.getPathString()).call();
        for (RevCommit rev: logs) {
          countDevelopers.add(rev.getAuthorIdent().getEmailAddress());
          count++;
        }
        jsonDataset.put("FileName", treeWalk.getPathString());
        jsonDataset.put("CountDevelopers", countDevelopers.size());
        jsonDataset.put("CountCommits", count);
        jsonDataset.put("LOC", countLines(treeWalk.getPathString()));
        commitDetails.put(jsonDataset);
      }
    }
    
  4. 现在,我想检索每个文件插入和删除的行数。

  5. 请帮忙。 提前感谢。

1 个答案:

答案 0 :(得分:5)

以下代码段比较两个提交并打印更改。 diffFormatter.scan()返回DiffEntry的列表,每个列表都描述了添加,删除或修改的文件。每个差异条目依次都有一个HunkHeader列表,这些列表会改变该文件中的变化。

// Create two commits to be compared
File file = new File( git.getRepository().getWorkTree(), "file.txt" );
writeFile( file, "line1\n" );
RevCommit oldCommit = commitChanges();
writeFile( file, "line1\nline2\n" );
RevCommit newCommit = commitChanges();

// Obtain tree iterators to traverse the tree of the old/new commit
ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
oldTreeIter.reset( reader, oldCommit.getTree() );
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset( reader, newCommit.getTree() );

// Use a DiffFormatter to compare new and old tree and return a list of changes
DiffFormatter diffFormatter = new DiffFormatter( DisabledOutputStream.INSTANCE );
diffFormatter.setRepository( git.getRepository() );
diffFormatter.setContext( 0 );
List<DiffEntry> entries = diffFormatter.scan( newTreeIter, oldTreeIter );

// Print the contents of the DiffEntries
for( DiffEntry entry : entries ) {
  System.out.println( entry );
  FileHeader fileHeader = diffFormatter.toFileHeader( entry );
  List<? extends HunkHeader> hunks = fileHeader.getHunks();
  for( HunkHeader hunk : hunks ) {
    System.out.println( hunk );
  }
}

我认为使用DiffEntryHunkHeader提供的信息,您应该能够获得所需的--shortstat