相当于JGit中的git diff

时间:2015-07-09 18:37:19

标签: git git-diff jgit

如何获取不属于存储库的文件,a.txt和b.txt的git diff a.txt b.txt结果?

我希望以git diff格式提供输出。此外,由于某些限制,我无法通过Java运行git命令。

1 个答案:

答案 0 :(得分:1)

JGit diff代码位于DiffFormatter及其关联的类中。如果仔细观察一下,您会发现代码并不意味着要对任意字节流进行区分。它通过提交,树等耦合到现有的存储库。

如果您不介意错误的文件名,可以使用此解决方法:

1)创建临时存储库

2)创建一个包含单个文件(名为ab.txt)的提交,该文件包含a.txt的内容

3)使用单个文件创建另一个提交 - 名称与上述文件相同 - 保存b.txt的内容

4)现在你可以使用JGit来区分两个提交

示例代码:

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