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

问题描述 投票:0回答:2

我试图弄清楚如何在 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
}

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

两个问题:

  1. 使用
    git.tagList().call()
    有什么问题吗?
  2. 确定标签是否带注释的正确方法是什么?
jgit
2个回答
0
投票

如果您运行 jgit-cookbook 中的示例 ReadTagForName,输出将包含以下内容:

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

因此您应该能够检查返回的

Ref
对象的实际类。如果是“RevCommit”,那么它是一个轻量级标签,如果是“RevTag”,那么它似乎是一个带注释的标签。


0
投票

在轻量级标签上,“剥离对象 ID”始终为空,因此您可以执行以下操作:

repository.getTags().stream().map(tag -> tag.getPeeledObjectId()  == null)).collect(Collectors.asList())

© www.soinside.com 2019 - 2024. All rights reserved.