4

I'd like to get the paths of the files changed (added, modified, or deleted) between two commits.

From the command line, I'd simply write

git diff --name-only abc123..def456

What is the equivalent way to do this with JGit?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Paul Draper
  • 78,542
  • 46
  • 206
  • 285

1 Answers1

10

You can use the DiffFormatter to get a list of DiffEntrys. Each entry has a changeType that specifies whether a file was added, removed or changed. An Entrys' getOldPath() and getNewPath() methods return the path name. The JavaDoc lists what each method retuns for a given change type.

ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
ObjectId oldTree = git.getRepository().resolve( "HEAD~1^{tree}" );
oldTreeIter.reset( reader, oldTree );
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
ObjectId newTree = git.getRepository().resolve( "HEAD^{tree}" );
newTreeIter.reset( reader, newTree );

DiffFormatter diffFormatter = new DiffFormatter( DisabledOutputStream.INSTANCE );
diffFormatter.setRepository( git.getRepository() );
List<DiffEntry> entries = diffFormatter.scan( oldTreeIter, newTreeIter );

for( DiffEntry entry : entries ) {
  System.out.println( entry.getChangeType() );
}

The above example lists the changed files between HEAD and its predecessor, but can be changed to compare arbitrary commits like abc^{tree}.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • Just a question - why oldTree is under "newer" revision? Whis it old if it is new in fact.? HEAD^{tree} means current head commit(tree) while HEAD~1^{tree} is parent commit of current head - so its 1 commit behind. – Antoniossss Oct 11 '18 at 12:31
  • You are right, `oldTree` and `newTree` should be changed. I've edited the post accordingly. – Rüdiger Herrmann Oct 11 '18 at 13:47
  • Uhh good to know it was a mistake. Thanks for the snippet. Just used it. – Antoniossss Oct 11 '18 at 15:03