Evens Evens - 10 months ago 117
Java Question

JGit How get list of RevCommit for DiffEntry

I get difference between two branches using JGit as follows:

ObjectReader reader = git.getRepository().newObjectReader();

CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();

Ref master = git.getRepository().exactRef(getRefBranchName( branchMaster) );
RevTree masterTree = new RevWalk(git.getRepository()).parseTree(master.getObjectId());
oldTreeIter.reset(reader, masterTree.getId());

Ref release = git.getRepository().exactRef(getRefBranchName( branchRelease));
RevTree releaseTree = new RevWalk(git.getRepository()).parseTree(release.getObjectId());
newTreeIter.reset(reader, releaseTree.getId());

List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

Then I can print differences in files as follows:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
DiffFormatter formatter = new DiffFormatter (outputStream);
for (DiffEntry entry: diffs){
System.out.println("Diff Entry: " + entry + ", from: " + entry.getOldId()+", to: " + entry.getNewId());
String diffText = outputStream.toString("UTF-8");

I saw all differences between two files in this branches, but how can I get all commits for this differences for certain
? I have not found a way to do it

Answer Source

A DiffEntry does not have 'a list of RevCommits'. It represents a single change to a file and describes whether a file was added, modified, or deleted. And a commit must not necessarily be the source of the change.

However, you already have pointers to the commits that the DiffEntries are computed from. It's master and release.

With ref.getObjectId() you can obtain the id of the commit that the ref currently points to.

To obtain a RevCommit that contains all metadata of the commits and points to its tree, you need to use a RevWalk like this:

try( RevWalk walk = new RevWalk( repository ) ) {
  RevCommit commit = walk.parseCommit( master.getObjectId() );

For more about JGit's diff API you may want to read thje article What’s the Difference? Creating Diffs with JGit