Search code examples
javajgitgit-diff

List of files changed between commits with JGit


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?


Solution

  • 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}.