区分JGit中的轻量级标签和带注释的标签

Distinguish between lightweight and annotated tags in JGit

我正在尝试找出如何区分 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;
}

这是对

的回答中包含的等效解决方案
RevTag tag;
try {
  tag = revWalk.parseTag(ref.getObjectId());
  // ref points to an annotated tag
} catch(IncorrectObjectTypeException notAnAnnotatedTag) {
  // ref is a lightweight (aka unannotated) tag
}

class org.eclipse.jgit.lib.Ref 有方法 getPeeledObjectId() 应该 return 在注释标签的情况下提交的 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,这比捕获异常要好得多。不幸的是,在每种情况下,方法 returns null

两个问题:

  1. 使用git.tagList().call()有什么问题吗?
  2. 找出标签是否带注释的正确方法是什么?

如果您 运行 示例 ReadTagForName in the jgit-cookbook 输出包含以下内容:

Commit: (class org.eclipse.jgit.revwalk.RevCommit)commit a3033aec313556ba4e1ef55a66167a35432a4bc1 1369660983 ------p
Tag: (class org.eclipse.jgit.revwalk.RevTag)tag 25f629b5e8ddfabd55650c05ffbb5199633b6df0 ------p

因此您应该能够检查返回的 Ref 对象的实际 class。如果是“RevCommit”就是轻量级标签,如果是“RevTag”就好像是注释标签