Search code examples
gitgit-diffjgit

Equivalent of git diff in JGit


How can I get the result for git diff a.txt b.txt, for files, a.txt and b.txt, that are not part of a repository?

I want the output in the format git diff provides. Also, I can't run git commands through Java due to some restrictions.


Solution

  • The JGit diff code is located in DiffFormatter and its associated classes. If you take a closer look, you'll see that the code isn't meant to diff arbitrary byte streams. It is coupled to a an existing repository with commits, trees, etc.

    If you don't mind the wrong file names, you can use this workaround:

    1) create a temporary repository

    2) create a commit with a single file (named ab.txt) that holds the contents of a.txt

    3) create another commit with a single file - named identical as the above file - that holds the contents of b.txt

    4) now you can use JGit to diff the two commits

    Example code:

    File file = new File( git.getRepository().getWorkTree(), "ab.txt" );
    writeFile( file, "line1\n" );
    RevCommit oldCommit = commitChanges();
    writeFile( file, "line1\nline2\n" );
    RevCommit newCommit = commitChanges();
    
    ObjectReader reader = git.getRepository().newObjectReader();
    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset( reader, oldCommit.getTree() );
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset( reader, newCommit.getTree() );
    
    DiffFormatter diffFormatter = new DiffFormatter( System.out );
    diffFormatter.setRepository( git.getRepository() );
    List<DiffEntry> entries = diffFormatter.scan( newTreeIter, oldTreeIter );
    diffFormatter.format( entries );
    diffFormatter.close();
    
    private RevCommit commitChanges() throws GitAPIException {
      git.add().addFilepattern( "." ).call();
      return git.commit().setMessage( "commit message" ).call();
    }
    
    private static void writeFile( File file, String content ) throws IOException {
      FileOutputStream outputStream = new FileOutputStream( file );
      outputStream.write( content.getBytes( "UTF-8" ) );
      outputStream.close();
    }