如何在Jgit中将文件列表作为提交的一部分 [英] How to get the list of files as a part of commit in Jgit

查看:62
本文介绍了如何在Jgit中将文件列表作为提交的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取提交中所有文件的列表.我有可用的提交ID.

I want to get the list of all the files which were part of a commit. I have the commit id available with me.

我查看了以下链接

如何获取以下文件的文件列表用JGit提交

并尝试了以下代码.

TreeWalk treeWalk = new TreeWalk( repository );
treeWalk.reset( commit.getId() );
while( treeWalk.next() ) {
  String path = treeWalk.getPathString();
  // ...
}
treeWalk.close();

和以下代码

try( RevWalk walk = new RevWalk( git.getRepository() ) ) {
  RevCommit commit = walk.parseCommit( commitId );
  ObjectId treeId = commit.getTree().getId();
  try( ObjectReader reader = git.getRepository().newObjectReader() ) {
    return new CanonicalTreeParser( null, reader, tree );
  }
}

使用上面的代码,我得到了分支中存在的所有文件的列表.我需要提交时删除,修改或添加的文件列表.

With the above code I get the list of all the files present in the branch. I need the list of files which are deleted, modified or added on a commit.

使用以下git命令,我成功获取了属于特定提交的文件列表

With the following git command I successfully get the list of files which were part of particular commit

git diff-tree --name-only -r <commitId>

我想从JGit获得同样的东西.

I want the same thing from JGit.

更新:我不想得到两次提交之间的区别,而只是作为提交一部分而更改的文件列表.

Update : I don't want to get the difference between two commits but only the list of files changed as a part of commit.

推荐答案

您可以使用Git.diff()命令.它需要两个Tree-Iterators:

You can use the Git.diff() command. It requires two Tree-Iterators:

    final List<DiffEntry> diffs = git.diff()
            .setOldTree(prepareTreeParser(repository, oldCommit))
            .setNewTree(prepareTreeParser(repository, newCommit))
            .call();

可以使用以下内容从commitId创建树迭代器:

A tree-iterator can be created from the commitId with the following:

    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(repository.resolve(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }

        walk.dispose();

        return treeParser;
    }

然后,您可以遍历结果列表并检索每个已更改/添加/删除的文件的详细信息.

Then you can iterate over the resulting List and retrieve details for each changed/added/removed file.

另请参见 jgit-cookbook 中进行了展示.

See also this sample in my jgit-cookbook for a runable showcase.

这篇关于如何在Jgit中将文件列表作为提交的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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