【发布时间】:2020-09-16 10:39:15
【问题描述】:
我试图弄清楚如何区分 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。
两个问题:
-
git.tagList().call()的使用有什么问题吗? - 确定标签是否为带注释的正确方法是什么?
【问题讨论】:
标签: jgit