[英]How to determine who last changed a file with JGit
There is a good cook-book receipt for JGit which describes how to blame the author of a specific line in a file. JGit有一个不错的烹饪书收据 ,其中描述了如何责怪文件中特定行的作者。
Now I want to know who last changed a file. 现在,我想知道谁最后更改了文件。 Iterating over all lines to find the last changed line looks a little bit not so elegant. 遍历所有行以查找最后更改的行,看起来并不那么优雅。 Ideas? 想法?
You can use the LogCommand
with a path filter like this: 您可以将LogCommand
与以下路径过滤器一起使用:
Iterable<RevCommit> iterable = git.log().addPath( "foo.txt" ).call();
RevCommit latestCommit = iterable.iterator().next();
The code looks for the latestCommit
that modified foo.txt
. 该代码查找修改了foo.txt
的latestCommit
。 I haven't tested the above snippet with merge commits or other commits that have more than one parent. 我尚未使用合并提交或具有多个父项的其他提交测试过以上代码段。
Note however that this solution potentially may leak resources: the RevWalk
which provides the iterator is created by the LogCommand
but never closed. 但是请注意 ,此解决方案可能会泄漏资源:提供迭代器的RevWalk
由LogCommand
创建,但从未关闭。
In order to avoid the resource leak you can manually iterate the history like so: 为了避免资源泄漏,您可以像这样手动迭代历史记录:
RevCommit latestCommit = null;
String path = "file.txt";
try( RevWalk revWalk = new RevWalk( git.getRepository() ) ) {
Ref headRef = git.getRepository().exactRef( Constants.HEAD );
RevCommit headCommit = revWalk.parseCommit( headRef.getObjectId() );
revWalk.markStart( headCommit );
revWalk.sort( RevSort.COMMIT_TIME_DESC );
revWalk.setTreeFilter( AndTreeFilter.create( PathFilter.create( path ), TreeFilter.ANY_DIFF ) );
latestCommit = revWalk.next();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.