使用JGit在两次提交之间更改的文件列表 [英] List of files changed between commits with JGit

查看:79
本文介绍了使用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 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() );
}

上面的示例列出了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆