1

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
psychorama
  • 323
  • 5
  • 17
  • Can you provide more information about the setting? git diff is based on the unix program `diff`, which suits very well the requirement to diff two files not in the repository. Probably that would be an option? – Jo Oko Jul 09 '15 at 18:43
  • The machine I'm running on, I can't run git commands on it, however if jgit has a way to achieve this, it'll be possible for me. – psychorama Jul 09 '15 at 19:29
  • I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older posts which still don't have answers. – Rüdiger Herrmann Jul 13 '15 at 15:18

1 Answers1

2

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();
}
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79