我有一个场景,我需要检查两个文件的内容是否相等。
我所拥有的是 JGIT 存储库的两个文件的 commitIds。
是否有可能使用(文件)对象的 commitIds 检查相等性,而无需完全比较内容。
查看RevObjectTest.java
测试类:
assertTrue(AnyObjectId.equals(a1, a2));
assertTrue(AnyObjectId.equals(b1, b2));
如果你有两个文件的两个 ObjectID,你可以使用org.eclipse.jgit.lib.AnyObjectId
util 类来比较 SHA1。
如果 SHA1 匹配,则文件的内容匹配,因为 SHA1 是内容的哈希。
要查找特定文件的 ObjectId,请遵循由centic9(Dominik Stadler)(也是Stack Overflow 用户)编写的优秀JGit 食谱中的ReadFileFromCommit.java:
ObjectId lastCommitId = repository.resolve(Constants.HEAD);
// a RevWalk allows to walk over commits based on some filtering that is defined
RevWalk revWalk = new RevWalk(repository);
RevCommit commit = revWalk.parseCommit(lastCommitId);
// and using commit's tree find the path
RevTree tree = commit.getTree();
System.out.println("Having tree: " + tree);
// now try to find a specific file
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create("README.md"));
if (!treeWalk.next()) {
throw new IllegalStateException("Did not find expected file 'README.md'");
}
ObjectId objectId = treeWalk.getObjectId(0);