How to: Use git tag and commit hash as version number for your application

Posted: 2011-12-21
Updated: 2011-12-21

It is a good practice to use a sane version number for your applications. For example, vx.y.z is a common paradigm. I will not debate the x.y.z vs x.y vs whatever. The purpose of those lines is to find a way to use git to populate the version number.

What we want is to be able to do something like:

1 git tag v1.0.0

And have v1.0.0 appears somewhere in our application.

This sounds simple, but it took me sometimes (I'm slow) before finding an elegant solution.

Let's say you want to output your build number/version into config.h.

First, you need to rename config.h to config.h.in, then add config.h to your .gitignore file. Only config.h.in will be checked in git.

Then, in your config.h.in, put something like that:

1 #define VERSION $$VERSION$$

After that, you need to include in your build process, something that will generate config.h, replacing the placeholder, here $$VERSION$$ with the version from git.

To get the version from git, I do (in ruby):

1 ver = `git describe --tags`.strip
2 ver = `git rev-parse HEAD`.strip if ver.empty?

When you have ver just use whatevery process to put it in config.h.

I do something like:

1 config = open("config.h.in").read
2 config.gsub!(/\$\$VERSION\$\$/m, ver)
3 f = open("config.h", "w")
4 f << config
5 f.close

Of course this is because my build system is in ruby. The only important part is NOT to check config.h within your version control.

You may also put the generation of config.h in a git hook.

blog comments powered by Disqus