[英]JGit: read the content of a file at a commit in a branch
I want to read the content of a file at a certain commit in a certain branch: I am currently, using this code to read the content of a file at a certain commit ignoring the branch. 我想在某个分支的某个提交中读取文件的内容:当前,我正在使用此代码在某个分支忽略该分支来读取文件的内容。
public static String readContentOfFileAtCommit(String commitStr, String fileName)
throws IOException {
String content = null;
ObjectId lastCommitId = currentRepo.resolve(commitStr);
try (RevWalk revWalk = new RevWalk(currentRepo)) {
RevCommit commit = revWalk.parseCommit(lastCommitId);
RevTree tree = commit.getTree();
try (TreeWalk treeWalk = new TreeWalk(currentRepo)) {
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(fileName));
if (!treeWalk.next()) {
throw new IllegalStateException("Did not find expected file:" + fileName);
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = currentRepo.open(objectId);
content = new String(loader.getBytes());
}
revWalk.dispose();
}
return content;
}
My goal is to get the content of a file at a certain commit that is done on a certain branch. 我的目标是在某个分支上执行的某个提交中获取文件的内容。
Different from most older VCS tools branch, a branch in Git is simply a lightweight movable pointer to one of these commits. 与大多数较旧的VCS工具分支不同,Git中的分支只是指向这些提交之一的轻量级可移动指针。 It does not "contain" any commits itself. 它本身并不“包含”任何提交。 In other words, it's only a simple file that contains the 40 character SHA-1 checksum of the commit it points to. 换句话说,它只是一个简单的文件,其中包含它指向的提交的40个字符的SHA-1校验和。 There's also a very illustrative example in Git - Branches in a Nutshell : 在Git中也有一个非常说明性的示例-坚果壳中的分支 :
As stated by Rüdiger Herrmann, while a commit is usually created on a branch, you cannot say that a commit "was done on a branch" after the fact. 如RüdigerHerrmann所述,尽管通常在分支上创建提交,但是您不能说事实之后“在分支上完成了”提交。 Branches may be added, deleted, renamed, or updated there after. 之后可以在其中添加,删除,重命名或更新分支。 For example, even if the branch or tag v1.0
is removed, the commit 98ca9
, 34ac2
, f30ab
are still there, and reachable by master
. 例如,即使在分支或标记v1.0
被移除,则提交98ca9
, 34ac2
, f30ab
仍然存在,并且通过到达master
。 I would suggest you to read the Pro Git (2nd Edition), Chapter 3.1 Git - Branches in a Nutshell for more detail. 我建议您阅读Pro Git(第二版)的第3.1章Git-简而言之分支 。
As for JGit, here's my implementation of reading path for a specific commit: 至于JGit,这是我对特定提交的读取路径的实现:
private String getContent(RevCommit commit, String path) throws IOException {
try (TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), path, commit.getTree())) {
ObjectId blobId = treeWalk.getObjectId(0);
try (ObjectReader objectReader = repo.newObjectReader()) {
ObjectLoader objectLoader = objectReader.open(blobId);
byte[] bytes = objectLoader.getBytes();
return new String(bytes, StandardCharsets.UTF_8);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.