java – 如何计算JGit中插入/删除的行
作者:互联网
当我们执行git log –shortstat时,我们得到插入,删除和更改的行数.就像是:
1 file changed, 9 insertions(+), 3 deletions(-)
请帮助我获取插入,删除和更改的行数.
>我正在进行存储库克隆以在本地计算机上获取git项目.这是相同的代码:
RepoClone repoClone=new RepoClone();
repoClone.repoCloner();
repository = builder.setGitDir(repoClone.repoDir).setMustExist(true).build();
>我甚至可以获得TreeWalk:
TreeWalk treeWalk=getCommitsTreeWalk();
>我能够检索文件名,每个文件的提交次数,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);
}
}
>现在,我想检索为每个文件插入和删除的行数.
请帮忙.
提前感谢.
解决方法:
以下代码片段比较两个提交并打印更改. diffFormatter.scan()返回DiffEntrys列表,每个列表描述添加,删除或修改的文件.每个差异条目依次有一个HunkHeaders列表,它会在该文件中产生变化.
// 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 );
}
}
我认为使用DiffEntry和HunkHeader提供的信息,您应该能够获得所需的–shortstat.
标签:java,git,jgit 来源: https://codeday.me/bug/20190519/1138113.html