How to make git describe use semver compatible tags only

2k Views Asked by At

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.

2

There are 2 best solutions below

1
hoijui On

The best option I found so far:

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

Because the --match flag only supports primitive globs, not full regex, this check only considers very simple semver's of the form integer.integer.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
0
hoijui On

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