'How to make git describe use semver compatible tags only

I want my git describe invocation to use only refs that conform to semantic versioning. To keep it simple, for now, I do not care about other options (like annotated tags only, branches, candidates, ...).

Example:

I have tagged an early/old commit with 1.1.1 (semver compatible), a more recent commit with my-software-2.2.2, and an even newer one with some-random-tag. I want my git describe invocation to only consider the 1.1.1 tag.

The main difficulty here, seems to be that the way to limit the tags by their name is based on globs, not regex.



Solution 1:[1]

The best option I found so far:

git describe \
    --match='[0-9]*.[0-9]*.[0-9]*' \
    --exclude='*[^0-9.]*'

It only considers very simple semver's of the form integer-dot-integer-dot-integer, disregarding other valid ones, like:

  • 2.0.0-rc.2
  • 2.0.0-rc.1
  • 1.0.0-beta
  • 1.0.0-alpha+001
  • 1.0.0+20130313144700
  • 1.0.0-beta+exp.sha.5114f85
  • 1.0.0+21AF26D3—-117B344092BD

Solution 2:[2]

An other option is to use the (core git independent) Go tool: git-describe-semver.

sample usage:

cd my-git-directory
docker pull ghcr.io/choffmeister/git-describe-semver:latest
docker run --rm -v $PWD:/workdir ghcr.io/choffmeister/git-describe-semver:latest

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hoijui
Solution 2 hoijui