Versioning Java Builds from Git Tags

Updated · 9 min read
mediumGit 2.53gitjavamavengradlegit-describereleasesversioning

Versioning from Git tags means that a build reads its version number from the repository's tags, instead of from a number typed into pom.xml or build.gradle.kts. The tag v1.2.0 on a commit makes that commit's build version 1.2.0, and builds of later commits get versions that say how far they are from the last release. The command behind it is git describe. It is used so that every JAR can be traced back to the exact commit it was built from, and so that releasing is as simple as creating a tag.

Think of a product's batch number. Printing it from the factory's own records, instead of writing it by hand on each box, means it is always right, and anyone can look up exactly which batch a box came from.

Syntax

Terminal
git describe [--tags] [--always] [--dirty] [<commit>]
OptionDescription
(none)It is used to name the commit after the nearest annotated tag, as <tag>-<commits since>-g<short ID>.
--tagsIt is used to also accept lightweight tags.
--alwaysIt is used to fall back to the short commit ID when no tag is found.
--dirtyIt is used to add -dirty when the working folder has uncommitted changes.
--abbrev=<n>It is used to choose the length of the short ID.
--match "v*"It is used to consider only tags matching a pattern.

Example 1: What git describe Prints

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo 'Term fee: $12,000' > fees.txt
git add fees.txt
git commit --quiet -m "Add the term fee"
git describe --always
git tag -a v1.0.0 -m "Fee Tracker 1.0.0"
git describe
Output
5c7eaa5
v1.0.0

Explanation: before any tag existed, --always printed the short commit ID. On the tagged commit, git describe prints just the tag name. Now Navika and Advitha keep working:

Terminal
echo 'Late fee: $250' >> fees.txt
git commit --quiet -am "Add the late fee"
echo 'Hostel fee: $9,000' >> fees.txt
git commit --quiet -am "Add the hostel fee" --author="Advitha Anamaneni <advitha@example.com>"
git describe
echo 'Bus fee: $1,500' >> fees.txt
git describe --dirty
git restore fees.txt
Output
v1.0.0-2-g1779152
v1.0.0-2-g1779152-dirty

Explanation: v1.0.0-2-g1779152 means "2 commits after v1.0.0, at commit 1779152" (the g stands for Git). With an uncommitted change, --dirty adds -dirty, a warning that this build doesn't match any commit exactly. Every one of these names identifies the code precisely.

Turning the Description into a Version

git describe --tags --dirtyVersion for the buildMeaning
v1.0.01.0.0A release
v1.0.0-2-g17791521.0.0-2-g1779152A development build after 1.0.0
v1.0.0-2-g1779152-dirty1.0.0-2-g1779152-dirtyA local build with uncommitted changes: never publish it

The leading v is a convention for tags; Java versions usually leave it out. In a shell, ${version#v} removes it:

Terminal
version=$(git describe --tags --always --dirty)
echo "Building version ${version#v}"
Output
Building version 1.0.0-2-g1779152
From git describe to a build version

Using the Version in Maven

Maven supports this through CI-friendly versions: the version in pom.xml is a property, given on the command line:

pom.xml
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>school.feetracker</groupId>
  <artifactId>fee-tracker</artifactId>
  <version>${revision}</version>
 
  <properties>
    <revision>0.0.0-SNAPSHOT</revision>
  </properties>
</project>
Terminal
./mvnw -Drevision="$(git describe --tags --always --dirty | sed 's/^v//')" package

Explanation: without -Drevision, the version is 0.0.0-SNAPSHOT, which marks a build nobody versioned on purpose. With it, the JAR becomes target/fee-tracker-1.0.0-2-g1779152.jar. If you publish the project to a Maven repository, add the flatten-maven-plugin so the published pom.xml contains the real number instead of ${revision}.

Using the Version in Gradle

In build.gradle.kts, Gradle can run git describe itself:

build.gradle.kts
version = providers.exec {
    commandLine("git", "describe", "--tags", "--always", "--dirty")
}.standardOutput.asText.get().trim().removePrefix("v")

Explanation: providers.exec runs the command in a way that works with Gradle's configuration cache, and removePrefix("v") turns v1.0.0 into 1.0.0. ./gradlew jar then writes build/libs/fee-tracker-1.0.0.jar on a release commit. Plugins such as com.palantir.git-version and the Axion release plugin do the same with more options.

Example 2: Making a Release

A release is an annotated tag on the commit to ship, pushed to the server. Annotated tags (see "Git Tag") record who released it and when, and plain git describe uses only them:

Terminal
git tag -a v1.1.0 -m "Fee Tracker 1.1.0: late and hostel fees"
git describe
git tag --list "v*" -n1
Output
v1.1.0
v1.0.0          Fee Tracker 1.0.0
v1.1.0          Fee Tracker 1.1.0: late and hostel fees

Then push the tag (git push origin v1.1.0, or git push --follow-tags to push commits and their annotated tags together). A CI workflow that starts on tags can build and publish the release:

.github/workflows/release.yml
on:
  push:
    tags: ["v*"]
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0
      - uses: actions/setup-java@v5
        with:
          distribution: temurin
          java-version: 25
      - run: ./mvnw --batch-mode -Drevision="${GITHUB_REF_NAME#v}" package

GITHUB_REF_NAME is the tag name, such as v1.1.0, so the JAR is version 1.1.0.

Example 3: A Changelog from the History

Good commit messages (see "Writing Good Commit Messages") make the changelog almost free. List what changed between two releases:

Terminal
git log --no-merges --format="- %s (%an)" v1.0.0..v1.1.0
git shortlog -s -n v1.0.0..v1.1.0
Output
- Add the hostel fee (Advitha Anamaneni)
- Add the late fee (Navika Anamaneni)
     1	Advitha Anamaneni
     1	Navika Anamaneni

Explanation: v1.0.0..v1.1.0 means the commits in 1.1.0 that weren't in 1.0.0. The --format turns each one into a list item with its author, ready for the release notes, and git shortlog -s -n counts commits per person. Teams that use the Conventional Commits style (feat:, fix:) can group the list by type with tools such as release-please or git-cliff, which read the same history.

Semantic Versioning in One Table

Most Java libraries follow semantic versioning, MAJOR.MINOR.PATCH:

ChangeExampleBump
A bug fix that changes no public APIFix the late fee rounding1.1.0 to 1.1.1
A new feature that keeps old code workingAdd the bus fee1.1.1 to 1.2.0
A change that breaks existing callersRename lateFee()1.2.0 to 2.0.0

Common Mistakes

Typing the version into pom.xml by hand for every release. It is easy to forget, and the JAR can't be traced to a commit. Let the tag set it.

Using lightweight tags for releases. Plain git describe ignores them. Use git tag -a, or --tags.

Shallow clones in CI. git describe needs the tags and enough history: use fetch-depth: 0.

Publishing a -dirty build. It contains changes no commit has. Make release builds fail if the version ends with -dirty.

Moving a tag after publishing. Users and Maven repositories already have the old one. Release a new version.

Under the Hood

git describe walks back from the commit through its ancestors, looking for the closest commit that an annotated tag points to (or any tag, with --tags). It counts how many commits it passed that aren't contained in the tagged commit, and prints <tag>-<count>-g<abbreviated ID>, using enough hex digits to be unique (at least 7). If the commit itself is tagged, the count is zero and only the tag is printed. --dirty runs the equivalent of git diff-index --quiet HEAD to check for uncommitted changes. Because the output depends only on the repository, the same commit always gets the same description on every computer that has the same tags.

Interview Corner

What does git describe print?

The nearest annotated tag, followed by the number of commits since it and the abbreviated commit ID, such as v1.0.0-2-g1779152. On a tagged commit, just the tag.

How do you set a Maven project's version from Git?

Use ${revision} as the version in pom.xml and run mvn -Drevision=$(git describe --tags | sed 's/^v//') package, with the flatten-maven-plugin when publishing.

Why does git describe fail in CI?

Shallow clones have no tags or too little history. Fetch the full history (fetch-depth: 0 on GitHub Actions) or at least the tags.

How do you generate a changelog between two releases?

git log --no-merges --format="- %s (%an)" v1.0.0..v1.1.0, and git shortlog -s -n v1.0.0..v1.1.0 for counts per author.

Practice

Challenge: a patch release. Fix a typo in a new commit after v1.1.0, print the description, tag it as v1.1.1, and print the description again.

What does Git print? Before you open the solution, decide both descriptions.

Show solution
Terminal
echo "Note: fees are in US dollars" >> fees.txt
git commit --quiet -am "Explain the currency"
git describe
git tag -a v1.1.1 -m "Fee Tracker 1.1.1"
git describe
Output
v1.1.0-1-gc61a0cf
v1.1.1

First v1.1.0-1-g with the new commit's short ID, one commit after 1.1.0. After tagging, just v1.1.1: a build of this commit is the 1.1.1 release.

Checkpoint. In a Maven or Gradle project, set the version from git describe, build once on a tagged commit and once after a new commit, and compare the JAR file names.

Quick check: versioning from Git tags

4 questions
1What does v1.0.0-2-g1779152 mean?
2Which option adds -dirty for uncommitted changes?
3Why might git describe fail on a CI server?
4Which kind of tag does plain git describe use?

Key Takeaways

Quick reference

CommandIt is used to
git describe --tags --always --dirtyDescribe the current commit
git tag -a v1.2.0 -m "<message>"Create a release tag
git push --follow-tagsPush commits and their annotated tags
git log --no-merges --format="- %s" v1.0.0..v1.1.0List changes between releases
git shortlog -s -n v1.0.0..v1.1.0Count commits per author

Was this tutorial helpful?

Lesson 101 of 106