Wednesday, March 21, 2012

Version numbers on software with git, tags and sed

After I moved from svn to git, I started doing some version numbers manually, as I felt I never had the time to figure out a good way to set version numbers using git. However, it's much easier and simpler than in svn, when done right.

Usually I use version numbers like this: 1.0.290, where 1 is major, 0 is minor and 290 the revision number.

I wanted to keep the same pattern when using git, as a lot of the software I maintain is moved from svn, where the revision was used directly from the svn repository.

Instead of having automatic revision numbers, I'm only going to increase them when I want to. That makes it possible to commit without increasing the revision number, which is really want I wanted to do.

Here's a quick and simple way to do it:
Tag your repository v1.0.290 (or similar)

To get the major, minor and revision number, git hash and number of commits since that tag:

echo "major:"
git describe --tags --long | sed "s/v\([0-9]*\).*/\1/"

echo "minor:"
git describe --tags --long | sed "s/v[0-9]*\.\([0-9]*\).*/\1/"

echo "revision:"
git describe --tags --long | sed "s/v[0-9]*\.[0-9]*\.\([0-9]*\).*/\1/"

echo "commits since tag:"
git describe --tags --long | sed "s/v[0-9]*\.[0-9]*\.[0-9]*-\([0-9]*\).*/\1/"

echo "git_hash:"
git describe --tags --long | sed "s/v[0-9]*\.[0-9]*\.[0-9]*-[0-9]*-g\(.*\)/\1/"

It should give an idea on how to get the data needed to update a project with the corresponding version info.