Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do the equivalent of "git diff --name-status" with jgit?

Tags:

java

jgit

I want to get a list of changed/added/deleted files between revision XXXXXX and HEAD. This is what I have so far:

String oldHash = "a97e5553e37a25bd1a3c99eab303145baed08dbd";
Git git = Git.open(new File("/tmp/jgit"));
Repository repository = git.getRepository();
ObjectId old = repository.resolve(oldHash);
ObjectId head = repository.resolve("HEAD");

// how do i get the trees from the obj. id?
List<<DiffEntry> diffs = git.diff().setNewTree(null).setOldTree(null).call();

for(DiffEntry diff : diffs) {
    // do stuff
}

Is this the right way to go about it and if so, how do I get the trees required for git.diff() ?

like image 582
Erik Avatar asked Dec 15 '11 13:12

Erik


1 Answers

You can get the tree id for HEAD and the hash by calling:

ObjectId head = repository.resolve("HEAD^{tree}");

and for the revision id:

ObjectId old = repository.resolve(oldHash + "^{tree}");

Once you have the tree ids you can create the tree iterators and get the diffs:

ObjectReader reader = repository.newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
oldTreeIter.reset(reader, oldId);
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset(reader, headId);
List<DiffEntry> diffs= git.diff()
                        .setNewTree(newTreeIter)
                        .setOldTree(oldTreeIter)
                        .call();
like image 61
Kevin Sawicki Avatar answered Sep 28 '22 01:09

Kevin Sawicki