List of files changed between commits with JGit

蹲街弑〆低调 提交于 2019-11-28 01:42:56

问题


I'd like to get the paths of the files changed (added, modified, or deleted) between two commits.

From the command line, I'd simply write

git diff --name-only abc123..def456

What is the equivalent way to do this with JGit?


回答1:


You can use the DiffFormatter to get a list of DiffEntrys. Each entry has a changeType that specifies whether a file was added, removed or changed. An Entrys' getOldPath() and getNewPath() methods return the path name. The JavaDoc lists what each method retuns for a given change type.

ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
ObjectId oldTree = git.getRepository().resolve( "HEAD~1^{tree}" );
oldTreeIter.reset( reader, oldTree );
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
ObjectId newTree = git.getRepository().resolve( "HEAD^{tree}" );
newTreeIter.reset( reader, newTree );

DiffFormatter diffFormatter = new DiffFormatter( DisabledOutputStream.INSTANCE );
diffFormatter.setRepository( git.getRepository() );
List<DiffEntry> entries = diffFormatter.scan( oldTreeIter, newTreeIter );

for( DiffEntry entry : entries ) {
  System.out.println( entry.getChangeType() );
}

The above example lists the changed files between HEAD and its predecessor, but can be changed to compare arbitrary commits like abc^{tree}.



来源:https://stackoverflow.com/questions/28785364/list-of-files-changed-between-commits-with-jgit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!