JGit:我可以在不检查的情况下找出某个特定标签是不是存在于 Git 存储库中吗?

Posted

技术标签:

【中文标题】JGit:我可以在不检查的情况下找出某个特定标签是不是存在于 Git 存储库中吗?【英文标题】:JGit: Can I find out whether or not a particular tag exists in a Git repository without checking it out?JGit:我可以在不检查的情况下找出某个特定标签是否存在于 Git 存储库中吗? 【发布时间】:2020-06-10 12:54:38 【问题描述】:

我需要用 Java 编写一段代码来测试某个特定标签是否存在于 Git 存储库中。

最明显的方法是:

git = Git.cloneRepository()
        .setURI(gitUri)
        .setDirectory(dir)
        .call();
git.checkout().setName(String.format("refs/tags/%s", version)).call();

如果标签version不存在,则会抛出异常。

但是这种方式需要我有一个目录 (dir) 将在其中签出存储库。

是否可以在不检查磁盘的情况下找出远程存储库中是否存在标签?如果是,我该怎么做?

【问题讨论】:

【参考方案1】:

LsRemoteCommand 能够列出远程仓库拥有的 refs。

该命令可以配置为包含这样的标签:

LsRemoteCommand ls = Git.lsRemoteRepository();
Collection<Ref> remoteRefs = ls
    .setRemote("url-to-remote-repo")
    .setHeads(true) // true by default, set to false if not interested in refs/heads/*
    .setTags(true)  // include tags in result
    .call();

如果您希望获取引用名称到Ref 对象的映射,您可以使用callAsMap() 执行命令。

【讨论】:

以上是关于JGit:我可以在不检查的情况下找出某个特定标签是不是存在于 Git 存储库中吗?的主要内容,如果未能解决你的问题,请参考以下文章