如何列出某个git分支中的所有标记

时间:2015-08-23 12:17:31

标签: git

我的git repo中有几个分支。我想知道是否有一个命令列出了某个分支中的所有标签而不是整个仓库中的所有标签。

我试过了git tag --contains。但它没有按预期工作。

图1,其中包含所有带散列的标签列表(标记的两个标签具有相同的散列/提交) enter image description here 图2,你可以看到我在一个名为" b"的分支上。 enter image description here 图3,我查询哪个分支包含两个标签的散列(两者都有相同的散列),并且它表示它们在分支上" b" (我目前正在使用的那个)enter image description here

图4,描述了分支标签,它只给了我一个标签enter image description here

图5,也描述了应该指向用两个标签标记的提交的哈希的标签,它只再次显示一个标签enter image description here

2 个答案:

答案 0 :(得分:8)

使用git tag --sort='creatordate' --merged列出可从HEAD访问/访问的所有标记,并按时间顺序对其进行排序。

如果您不想要HEAD,可以指定引用,例如git tag --sort='creatordate' --merged mybranch

答案 1 :(得分:7)

要打印指向某个提交的所有标记,您可以执行以下操作:

git for-each-ref refs/tags | grep HASH

或者,如果您使用的是Windows并且不使用Cygwin或类似程序:

git for-each-ref refs/tags | find "HASH"

如果您只想要标记名称,则无法使用Git' --format,因为我们需要它来进行grep' ing。因此,我们需要在最后一步(Linux / Cygwin)中删除我们不感兴趣的内容:

git for-each-ref refs/tags | grep HASH | sed -r "s/.*refs\/tags\/(.*)/\1/"

关于最初的问题:

这会迭代所有分支中的所有标记,询问git哪些分支包含每个标记并根据提供的分支名称进行过滤 - 但要注意,它超慢

git for-each-ref refs/tags --format "%(refname)" | while read x
do
    if git branch --contains $x | grep -q "^[ *] master$"
        then echo $x
    fi
done

以下taken from another answer要快得多:

git log --simplify-by-decoration --decorate --pretty=oneline "master" | fgrep 'tag: '

...但如果多个标签指向同一个提交,它将产生:

 (HEAD, tag: Test-Tag1, tag: Test-Tag2, Test-Tag3, fork/devel, devel)
 (tag: Another-Tag)
 (tag: And-Another)

(指向同一提交的三个标签Test-Tag*

我编写了一个Python脚本,仅输出标记名称,每行一个(仅在Windows上测试):

import os
from subprocess import call

print("-" * 80)

dirpath = r"D:\Projekte\arangodb" # << Put your repo root path here!

tagdir = os.path.join(dirpath, ".git", "refs", "tags")
commitspath = os.path.join(dirpath, "_commit_list.tmp")

# could probably read from stdin directly somewhow instead of writing to file...
# write commits in local master branch to file
os.chdir(dirpath)
os.system("git rev-list refs/heads/master > " + commitspath)

tags = {}
for tagfile in os.listdir(tagdir):
    with open(os.path.join(tagdir, tagfile), "r") as file:
        tags[file.read().strip()] = tagfile

tags_set = set(tags)

commits = {}
with open(commitspath, "r") as file:
    for line in file:
        commits[line.strip()] = 1
os.remove(commitspath)

commits_set = set(commits)

for commit in sorted(commits_set.intersection(tags_set), key=lambda x: tags[x]):
    print(tags[commit])

结果:

Test-Tag1
Test-Tag2
Test-Tag3
Another-Tag
And-Another

也可以选择为每个标签打印提交哈希,只需将最后一行修改为print(commit, tags[commit])即可。顺便说一句,这个剧本表现得非常好!

理想情况下,git会支持以下命令,以避免所有这些变通方法:

git tag --list --branch master