Skip to content

Git Describe: Build Versioning from Tags ​

git describe turns the question "where is this commit relative to the nearest tag" into a single, deployable string. It is the standard answer to "what version is this build?" for CI/CD pipelines, artifact registries, and incident channels. This guide covers the internals, the edge cases, and the automation patterns that make git describe work at scale.

What it answers ​

"I have a commit SHA. What is the human-readable version of this build?"

"Is this artifact built from a release tag, a pre-release candidate, or something in between?"

"My monorepo has tags for five different components. How do I describe a specific project's version without crossing tag namespaces?"

How it works ​

git describe walks back from the current commit (or a given commit) along the first-parent history until it finds an annotated tag. It then reports:

<nearest-tag>-<commits-since>-g<abbrev-sha>
$ git describe --tags --always
v2.3.0-4-gabc1234
#  |     |  |
#  |     |  +- 'g' prefix + abbreviated commit SHA
#  |     +---- number of commits since the tag
#  +---------- nearest tag reached by walking backwards

The -g prefix distinguishes the SHA from a hex number. Without it, abc1234 could be a version string or a commit — the g removes ambiguity.

Default behavior ​

By default git describe only considers annotated tags. Lightweight tags are ignored unless you pass --tags. This is deliberate: annotated tags are real Git objects with a tagger, date, and message. Lightweight tags are just pointers and are often used for temporary markers.

bash
git describe                    # annotated tags only
git describe --tags             # all tags (annotated + lightweight)
git describe --all              # any ref (branches, tags, HEAD)

The fallback chain ​

When no tag is reachable from the given commit, git describe errors out:

fatal: No tags can describe '<sha>'.
Try --always, or create some tags.

--always changes this: if no tag matches, it falls back to the abbreviated SHA alone:

bash
git describe --tags --always
# abc1234

Always use --always in CI scripts. A fresh repo with no tags should not crash your build pipeline.

Matching and filtering ​

Namespace isolation ​

In a monorepo with multiple components, each component should use its own tag prefix:

api/v1.2.0
web/v3.0.1
shared/v0.5.0

Use --match to scope the search:

bash
git describe --tags --match 'api/*'
# api/v1.2.0-3-gabc1234

Without --match, describe picks the nearest tag regardless of prefix. In a monorepo where api/ and web/ tags are interleaved, the wrong tag can produce a version string that looks valid but points to the wrong component's release.

Excluding tags ​

Use --exclude to skip certain patterns:

bash
git describe --tags --exclude '*-rc*' --exclude '*-alpha*'

This finds the nearest stable release tag, ignoring pre-release tags. Useful when you want the version string to reflect only production releases.

Multiple match patterns ​

You can repeat --match to specify multiple acceptable patterns:

bash
git describe --tags --match 'v*' --match 'release/*'

First-parent mode ​

--first-parent changes how describe walks history. By default it follows all parents. With --first-parent it only follows the primary merge lineage:

bash
git describe --tags --first-parent

This matters in repos with a "merge-up" workflow where feature branches are merged into main. Without --first-parent, describe might walk into a long-lived feature branch's tags instead of main's release tags.

When to use it:

  • Release branches with periodic merges from develop
  • Repos where feature branches have their own tags
  • CI pipelines that always want the release tag, not a feature branch tag

When not to use it:

  • Linear history (squash-merge or rebase-merge workflows)
  • Repos without merge commits at all

Candidate count and debug output ​

How many tags does describe evaluate? ​

By default git describe looks at up to 10 candidate tags. If it cannot find the closest one among them, it reports the closest one it found. Increase the candidate pool for repos with many tags:

bash
git describe --tags --candidates=50

This is rarely needed, but if you see describe returning a suboptimal tag (one that is not the actual nearest), the fix is usually to raise --candidates.

Debug mode ​

bash
git describe --tags --debug HEAD

Output:

searching to describe HEAD
finished search at commit abc1234
     annotated tag v2.3.0 (100 commits away)
     annotated tag v2.2.0 (200 commits away)
best candidate: v2.3.0

--debug shows every tag describe considered and the distance calculation. Use it when the output is surprising — it tells you exactly which tags were evaluated and why one won.

Abbreviation length ​

The default SHA abbreviation is 7 characters. For repos with many objects, raise it to avoid collision:

bash
git describe --tags --abbrev=12

Or use --abbrev=0 to omit the SHA entirely:

bash
git describe --tags --abbrev=0
# v2.3.0

This returns only the tag name. Useful when you are exactly on a tag and want just the version number without commit suffix.

Dirty tree detection ​

The --dirty flag appends -dirty when the working tree has uncommitted changes:

bash
git describe --tags --always --dirty
# v2.3.0-4-gabc1234-dirty

A build from a dirty tree is not reproducible. Bake --dirty into every CI script. If the build artifact has -dirty in its version, someone built from a checkout that was not clean — either a developer's machine or a CI runner with leftover files.

Containing check ​

git describe --contains answers the reverse question: "which tag contains this commit?"

bash
git describe --contains abc1234
# v2.3.0~4

This means the commit abc1234 is an ancestor of the tag v2.3.0, four commits before it. The ~4 suffix is the distance. This is useful for changelog generation: given a commit, which release will ship it.

All mode ​

--all describes from any ref, not just tags:

bash
git describe --all
# heads/feature-search-3-gabc1234

This falls back to branch names when no tag is reachable. Rarely used in CI, but useful for debugging: it tells you which branch a detached HEAD commit belongs to.

CI/CD integration patterns ​

Docker image tags ​

bash
VERSION=$(git describe --tags --always --dirty)
docker build --build-arg VERSION="$VERSION" -t myapp:"$VERSION" .

The version string becomes the image tag. Every build has a unique, traceable tag that maps back to a commit.

Go linker injection ​

go
var version = "dev"

func main() {
    fmt.Println("version:", version)
}
makefile
VERSION := $(shell git describe --tags --always --dirty)
go build -ldflags "-X main.version=$(VERSION)" -o bin/app .

Python package version ​

python
# setup.py or pyproject.toml
import subprocess
version = subprocess.check_output(
    ["git", "describe", "--tags", "--always", "--dirty"],
    cwd=os.path.dirname(__file__)
).decode().strip()

Artifact filename ​

bash
VERSION=$(git describe --tags --always --dirty --abbrev=12)
tar czf "myapp-${VERSION}.tar.gz" dist/

Status badge / API endpoint ​

bash
echo "{\"version\": \"$(git describe --tags --always --dirty)\"}" > public/version.json

Edge cases and pitfalls ​

SituationWhat describe doesMitigation
No tags existFatal errorAdd --always to fall back to SHA
Only lightweight tagsIgnores themUse --tags or convert to annotated
Wrong tag matched from monorepoVersion string uses wrong component prefixUse --match 'component/*'
Long-lived feature branch has tagsDescribe walks into branch tagsUse --first-parent
Hundreds of tagsSlow evaluationRaise --candidates or use --match to narrow
Shallow cloneMissing tag historyDescribe may fail; use --always and accept SHA fallback
Detached HEAD (CI runner)Works normallyDescribe does not depend on branch names
Multiple tags on same commitPicks the one with the highest version (alphabetically)Use --match to control which tag wins
Tag deleted after releaseDescribe from that commit finds next tagAlways use annotated tags; never delete published tags
Build from a dirty checkoutVersion gets -dirty suffixBlock dirty builds in CI or strip -dirty only for dev builds

Performance notes ​

  • git describe walks commit ancestry. For deep histories (100k+ commits), this can take hundreds of milliseconds. The commit-graph speeds this up significantly — run git maintenance start on repos used in CI.
  • On a repo with the commit-graph enabled, describe on HEAD is under 10ms even on large repos.
  • --match filters are applied during the walk, not before it. A narrow --match pattern does not make describe faster — it still walks the same number of commits, it just rejects non-matching tags.

Quick reference ​

bash
git describe                          # Nearest annotated tag + commit distance
git describe --tags                   # Include lightweight tags
git describe --all                    # Include branches and other refs
git describe --always                 # Fall back to SHA if no tag
git describe --dirty                  # Append -dirty if tree is modified
git describe --abbrev=0               # Tag only, no SHA
git describe --abbrev=12              # Longer SHA abbreviation
git describe --match 'v*'             # Only tags matching glob pattern
git describe --exclude '*-rc*'        # Skip pre-release tags
git describe --first-parent           # Follow only primary merge parent
git describe --candidates=50          # Evaluate more tag candidates
git describe --debug                  # Show candidate evaluation
git describe --contains <commit>      # Which tag contains this commit

Next steps ​

git describe is one input to a versioning strategy. Read the tagging strategy guide for the full picture on semver, pre-release tags, and signed releases. Then see the revision specifiers guide for the other ways Git can name commits by position, ancestry, and pattern.

Git Master — Git Reference for Every Skill Level