Version numbers from Git

Remember SVN $Rev$ substitution?

It was really useful for version numbers.

Example:

version = "1.0.$Rev$"

version = "1.0.$Rev: 374 $"

(Maybe not as useful as all that...)

String parsing to the rescue:

"1.0.$Rev: 374 $""1.0.374"

Which looks good in an About dialog.

Makes bug reports much easier to reproduce.

Then along came Git.

Git doesn't have nice, numeric revision numbers.

It has ugly-looking commit hashes like 8fb4da5.

So, how can you get nice version numbers out of Git?
Enter the  git describe  command.

$ git describe

v1.0-42-g8fb4da5

Breakdown of a  git describe  version number:

v1.0

Latest
git tag

-

42

Commits
since tag

-

g8fb4da5

Hash of
HEAD commit

This means we're 42 commits ahead of version 1.0.

Note: only annotated tags will be used.

Two kinds of git tags: annotated and lightweight
  • git taglightweight tag (default)
  • git tag -aannotated tag
  • git tag -sannotated and signed tag

Use lightweight tags for private tags,
and signed tags for releases.

BTW, always use git push --follow-tags:
It pushes only annotated tags.

NEVER use git push --tags:
Lightweight tags should not leave your repo.

So what?

"Single source of truth" for your version numbers.

Change the version number in one place,
and it changes everywhere.

No more "update version number" commits.
Just Tag It™.

Make your build process help you.

Run git describe early in the build process,
then use text replacement to put the version number where it needs to be.

  • AssemblyInfo.cs
  • package.json
  • __setup__.py
  • ... and so on ...
I wrote a simple tool to help with this.

It runs git describe and parses the result.

It outputs four environment variables:
GIT_VN_FULL v1.0-42-g8fb4da5
GIT_VN_TAG 1.0 (no "v")
GIT_VN_COMMITS 42
GIT_VN_SHA 8fb4da5 (no "g")

Then you use those in your later build process.

Bonus TeamCity integration

If you're using TeamCity, the tool's output
is in the right format for TeamCity to pick up.

If you're not using TeamCity, you'll need to
set up the environment variables youself.

E.g., output the tool's output to a shell script
and do source myscript.sh

Script requirements
  • Python installed on your build machine
  • Git installed and in your build machine's PATH
    (so running git describe just works)
  • That's it.
Get the script

And remember:

  • Use git tag -s to tag your releases
  • Recommended tag format: v#.#.#
    E.g., v3.1.4
  • Always push with git push --follow-tags

P.S. When your needs outgrow this simple tool,
the gitversion tool might be what you need next.