如何获取当前提交的标记

我有一个存储库,它在同一个提交上有多个标记。例如:

commit #3 <--- TAG1 / TAG2 / TAG3


|


commit #2 <--- TAG4/ TAG5


|


commit #1 <--- TAG6/ TAG7

我想找出特定提交上的标记。例如,如果我检查提交1,我希望得到标记6和标记7。

我试过了:

git checkout <commit 1>
git tag --contains

显示标签1-7。

git checkout <commit 1>
git describe --tags HEAD

只显示标签6。

在 Git 中进行此操作的正确方法是什么?

51644 次浏览

This is not ideal, but perhaps helpful:

$ git log -n 1 --decorate --pretty=oneline

You could play around with the format to get exactly what you want.

Some improvements on William's answer:

git config --global alias.tags 'log -n1 --pretty=format:%h%d'

The output looks like this:

~$ git tags
7e5eb8f (HEAD, origin/next, origin/master, origin/HEAD, master)
~$ git tags HEAD~6
e923eae (tag: v1.7.0)

I guess maybe git has had some options added since this question was asked, but since it still comes in pretty high on google, I thought I'd add that this way works nicely:

git tag -l --contains HEAD

Or replace HEAD with any other valid commit reference you like.

This will print a newline separated list of tags if the HEAD contains any tags, and print nothing otherwise, so you would get:

TAG6
TAG7

And of course there are lots of nice ways with various other shell tools that you can format that output once you have it...

Here's a refinement of @JoshLee's answer, which manipulates the output to list only tags (not branches, nor HEAD) and strips the word 'tag:' and decorative punctuation. This is useful if you are scripting something up which needs to find the current tags (e.g. put them in your prompt):

git log -n1 --pretty="format:%d" | sed "s/, /\n/g" | grep tag: | sed "s/tag: \|)//g"

Example output:

$ git log -n 1 --decorate=short
commit a9313...c7f2 (HEAD, tag: v1.0.1, tag: uat, mybranch)
...
$ git log -n1 --pretty="format:%d" | sed "s/, /\n/g" | grep tag: | sed "s/tag: \|)//g"
v1.0.1
uat

This displays the commit id of HEAD, as well as any branches or any tags that also happen to be exactly at HEAD.

git reflog --decorate -1

Sample output:

484c27b (HEAD, tag: deployment-2014-07-30-2359, master, origin/master) HEAD@{0}: 484c27b878ca5ab45185267f4a6b56f8f8d39892: updating HEAD

For completion (thanks to Ciro Santili answer), git tag has got the option --points-at that does exactly what OP is asking.

git tag --points-at HEAD

It does not have the effect of also listing the tags put on forward commits (as Jonathan Hartley stated in his comment regarding git tag --contains).

git tag --points-at

--points-at

Only list tags of the given object (HEAD if not specified). Implies --list.

from https://git-scm.com/docs/git-tag

I'm doing git tag -l | grep $(git describe HEAD) it returns the tag of the latest commit, or nothing if the last commit isn't tagged