Search code examples
javascriptgitsimple-git

How to get latest tag of git repository


I'm using simple-git and I need to get the commit hash of the latest tag.

So far I did it this way:

const tags: string = await git.tag({
    '--list': null,
    '--format': '%(objectname:short)'
})
const commitLastTag = tags.trim().split('\n').pop() || 'HEAD~1'

First it was working, but now there is a problem, which is caused by sorting. tags has the value (if not using --format):

v3.0.0
v3.0.1
v3.0.2
v3.0.3
v3.1.0
v3.10.0
v3.11.0
v3.2.0
v3.3.0
v3.4.0
v3.5.0
v3.5.1
v3.6.0
v3.6.1
v3.6.2
v3.6.3
v3.7.0
v3.7.1
v3.7.2
v3.8.0
v3.9.0
v3.9.1
v3.9.2
v3.9.3

As you can see now I do not get the latest tag - which should be v3.11.0

In the console I would do git describe --abbrev=0 --tags to get the latest tag, but there is no describe in simple-git.


Solution

  • Like sort -V, git tag has a similar option --sort=version:refname or --sort=v:refname to sort version numbers. It's a special instance of --sort=<key>.

    If the version number is more complicated, the configuraion value versionsort.suffix could help.

    I'm not familiar with Javascript. But I guess its sort functions support a custome callback that determines the order of elements like cmp in the function sorted(cmp=None, ...) of Python. If it has such callbacks, I think you can sort any versions.