Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latest git tag from the current commit

Tags:

git

git-tag

I am trying to get the latest git tag from a certain point in my tree.

The tree looks as follows:

* 334322c|2016-12-06| (tag: 0.1265, tag: 0.1264) (18 hours ago)
* 739392e|2016-12-06| (HEAD -> testbranch, tag: 0.1263, tag: 0.1262) (19 hours ago)
* 8ec1add|2016-12-06| (tag: 0.1261, tag: 0.1260, tag: 0.1259) (20 hours ago)
* 5b2667b|2016-12-06| (tag: 0.1258) (21 hours ago)
* c7ff4bc|2016-12-06| (tag: 0.1257, tag: 0.1256) (22 hours ago)

0.1263 is the git tag I am looking for.

When on 739392e using git describe --tags returns only 0.1262 which is the first tag on that commit, and I'm not getting all the candidates.

When on 739392e using git describe --tags $(git rev-list --tags --max-count=1) returns 0.1265, the latest tag on the tree (regardless of where the HEAD is).

like image 466
Rotemmiz Avatar asked Nov 08 '22 05:11

Rotemmiz


1 Answers

If you can sort tags on name (which seems reasonable?) you can use the following command:

git tag --points-at HEAD --sort -version:refname | head -1

If not first check if committerdate or authordate is set on your tags:

git tag --points-at HEAD --format='%(*committerdate:iso) %(*authordate:iso) %(refname) %(*objectname) %(objectname)'

This will output something like this:

2018-05-28 09:58:06 +0200 2018-05-28 09:58:06 +0200 refs/tags/3.11.47 55a4f6de2b1466d1a2ee60acc53aa12fd5ad07b3 914ac376102a6c7f189453fbcd8737db32b90693
2018-05-28 09:58:06 +0200 2018-05-28 09:58:06 +0200 refs/tags/3.11.46 55a4f6de2b1466d1a2ee60acc53aa12fd5ad07b3 e0d37427b89fbd6c3baa898a1264a9ba3e3ff7f

As you can see from this example, both tags have identical committerdate and authordate, meaning we cannot sort on those fields. However if they are set correctly you can use this command:

git tag --points-at HEAD --sort -version:creatordate | head -1

From git help tag:

--sort=<key> Sort based on the key given. Prefix - to sort in descending order of the value. You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key. Also supports "version:refname" or "v:refname" (tag names are treated as versions). The "version:refname" sort order can also be affected by the "versionsort.suffix" configuration variable. The keys supported are the same as those in git for-each-ref. Sort order defaults to the value configured for the tag.sort variable if it exists, or lexicographic order otherwise. See git-config(1).

And from git help for-each-ref:

For commit and tag objects, the special creatordate and creator fields will correspond to the appropriate date or name-email-date tuple from the committer or tagger fields depending on the object type. These are intended for working on a mix of annotated and lightweight tags.

like image 144
awi Avatar answered Nov 15 '22 04:11

awi