Equivalent of git diff in JGit

孤人 提交于 2019-12-12 02:57:33

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/31325613/equivalent-of-git-diff-in-jgit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!