如何用jgit做相当于“git diff --name-status”的操作?

时间:2011-12-15 13:14:39

标签: java jgit

我想获取修订版XXXXXX和HEAD之间已更改/添加/删除文件的列表。这就是我到目前为止所做的:

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
}

这是正确的方法,如果是这样,我如何获得git.diff()所需的树?

1 个答案:

答案 0 :(得分:9)

您可以通过调用:

获取HEAD和哈希的树ID
ObjectId head = repository.resolve("HEAD^{tree}");

和修订版ID:

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

获得树ID后,您可以创建树迭代器并获取差异:

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