问题描述
我试图弄清楚如何在JGit中区分轻量级标签和带注释的标签,而又不捕获任何异常。在我的特殊情况下,我需要区别对待以获取给定提交的所有标记名。
public List<String> getTagNamesOfCommit(String commitHash) throws Exception {
List<String> tagNames = new ArrayList<>();
RevWalk walk = new RevWalk(repository);
List<Ref> tagList = git.tagList().call();
for (Ref tag : tagList) {
ObjectId peeledobjectId = tag.getPeeledobjectId();
try {
// Try to get annotated tag
RevTag refetchedTag = walk.parseTag(tag.getobjectId());
RevObject peeled = walk.peel(refetchedTag.getobject());
if (peeled.getId().getName().equals(commitHash)) {
tagNames.add(Repository.shortenRefName(tag.getName()));
}
} catch(IncorrectObjectTypeException notAnAnnotatedTag) {
// Tag is not annotated. Yes,that's how you find out ...
if (tag.getobjectId().getName().equals(commitHash)) {
tagNames.add(Repository.shortenRefName(tag.getName()));
}
}
}
walk.close();
return tagNames;
}
这是此question
的答案中包含的等效解决方案RevTag tag;
try {
tag = revWalk.parseTag(ref.getobjectId());
// ref points to an annotated tag
} catch(IncorrectObjectTypeException notAnAnnotatedTag) {
// ref is a lightweight (aka unannotated) tag
}
类org.eclipse.jgit.lib.Ref
具有方法getPeeledobjectId()
,该方法应在带注释的标签的情况下返回提交的ID。
* return if this ref is an annotated tag the id of the commit (or tree or
* blob) that the annotated tag refers to; {@code null} if this ref
* does not refer to an annotated tag.
这样,我可以检查null,这比捕获异常好得多。不幸的是,该方法在每种情况下都会返回null
。
两个问题:
解决方法
如果您在ReadTagForName中运行示例jgit-cookbook,则输出将包含以下内容:
Commit: (class org.eclipse.jgit.revwalk.RevCommit)commit a3033aec313556ba4e1ef55a66167a35432a4bc1 1369660983 ------p
Tag: (class org.eclipse.jgit.revwalk.RevTag)tag 25f629b5e8ddfabd55650c05ffbb5199633b6df0 ------p
因此,您应该能够检查返回的Ref
对象的实际类。如果它是“ RevCommit”,则是轻量级标签;如果是“ RevTag”,则它似乎是带注释的标签。