使用JGit在两次提交之间更改的文件列表 [英] List of files changed between commits with JGit
问题描述
我想获取两次提交之间更改(添加,修改或删除)的文件的路径.
I'd like to get the paths of the files changed (added, modified, or deleted) between two commits.
在命令行中,我只是写
git diff --name-only abc123..def456
使用JGit进行此操作的等效方法是什么?
What is the equivalent way to do this with JGit?
推荐答案
您可以使用 DiffFormatter
来获取 DiffEntry
的列表.每个条目都有一个changeType,用于指定是添加,删除还是更改文件. Entry
s的 getOldPath()
和 getNewPath()
方法返回路径名. JavaDoc列出每种方法针对给定的更改类型所返回的内容.
You can use the DiffFormatter
to get a list of DiffEntry
s. Each entry has a changeType that specifies whether a file was added, removed or changed. An Entry
s' 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() );
}
上面的示例列出了 HEAD
及其前身之间已更改的文件,但可以进行更改以比较诸如 abc ^ {tree}
之类的任意提交.
The above example lists the changed files between HEAD
and its predecessor, but can be changed to compare arbitrary commits like abc^{tree}
.
这篇关于使用JGit在两次提交之间更改的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!