What\'s the simplest way to get the most recent tag in Git?
git tag a HEAD
git tag b HEAD^^
git tag c HEAD^
git tag
output:
"Most recent" could have two meanings in terms of git.
You could mean, "which tag has the creation date latest in time", and most of the answers here are for that question. In terms of your question, you would want to return tag c
.
Or you could mean "which tag is the closest in development history to some named branch", usually the branch you are on, HEAD
. In your question, this would return tag a
.
These might be different of course:
A->B->C->D->E->F (HEAD)
\ \
\ X->Y->Z (v0.2)
P->Q (v0.1)
Imagine the developer tag'ed Z
as v0.2
on Monday, and then tag'ed Q
as v0.1
on Tuesday. v0.1
is the more recent, but v0.2
is closer in development history to HEAD, in the sense that the path it is on starts at a point closer to HEAD.
I think you usually want this second answer, closer in development history. You can find that out by using git log v0.2..HEAD
etc for each tag. This gives you the number of commits on HEAD since the path ending at v0.2
diverged from the path followed by HEAD.
Here's a Python script that does that by iterating through all the tags running this check, and then printing out the tag with fewest commits on HEAD since the tag path diverged:
https://github.com/MacPython/terryfy/blob/master/git-closest-tag
git describe
does something slightly different, in that it tracks back from (e.g.) HEAD to find the first tag that is on a path back in the history from HEAD. In git terms, git describe
looks for tags that are "reachable" from HEAD. It will therefore not find tags like v0.2
that are not on the path back from HEAD, but a path that diverged from there.