pranay jain
pranay jain

Reputation: 372

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

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.

Upvotes: 2

Views: 2306

Answers (1)

centic
centic

Reputation: 15872

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.

Upvotes: 1

Related Questions