File diff against the last commit with JGit

后端 未结 1 1804
别那么骄傲
别那么骄傲 2021-01-06 05:29

I am trying to use JGit to get the differences of a file from the last commit to the most recent uncommitted changes. How can I do this with JGit? (using the command line wo

相关标签:
1条回答
  • 2021-01-06 05:39

    The following setup works for me:

    DiffFormatter formatter = new DiffFormatter( System.out );
    formatter.setRepository( git.getRepository() );
    AbstractTreeIterator commitTreeIterator = prepareTreeParser( git.getRepository(),  Constants.HEAD );
    FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
    List<DiffEntry> diffEntries = formatter.scan( commitTreeIterator, workTreeIterator );
    
    for( DiffEntry entry : diffEntries ) {
      System.out.println( "Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId() );
      formatter.format( entry );
    }
    

    The uncommitted changes are made accessible trough the FileTreeIterator. Using formatter.scan() instead of the DiffCommand has the advantage that the formatter is set up properly to handle the FileTreeIterator. Otherwise you will get MissingObjectExceptions as the formatter tries to locate changes from the work tree in the repository.

    0 讨论(0)
提交回复
热议问题