JGit中git diff的等效项 [英] Equivalent of git diff in JGit

查看:437
本文介绍了JGit中git diff的等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我想要git diff提供的格式的输出.另外,由于某些限制,我无法通过Java运行git命令.

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

推荐答案

JGit差异代码位于DiffFormatter及其关联的类中.如果仔细研究,您会发现该代码并非旨在区分任意字节流.它与具有提交,树等的现有存储库耦合.

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)创建一个临时存储库

1) create a temporary repository

2)使用包含a.txt

3)用一个文件创建另一个提交-与上述文件相同,该文件保存b.txt

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

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

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

示例代码:

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

这篇关于JGit中git diff的等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆