How to get the list of files as a part of commit in Jgit

别等时光非礼了梦想. 提交于 2020-12-26 03:59:27

问题


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

I looked into the following link

How to get the file list for a commit with JGit

and tried the following code.

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

and following code

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.

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>

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.


回答1:


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();

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.

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



来源:https://stackoverflow.com/questions/46727610/how-to-get-the-list-of-files-as-a-part-of-commit-in-jgit

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