Thursday, 2 May 2013

Including (or referring to) the git revision in your maven build


I am writing customized test ware for one of my personal projects (more on it in another post). The test ware does a few things and at the end stores the test results in a relational database. I wanted to be able to link each database record to the specific git commit from which the code under test was produced. I have used a similar technique with svn in the past but did not know how to do this with git. Also I wanted to automate it using my CI pipeline (maven, Jenkins, Sonar).


After a bit of googling I found Mattias Severson's excellent post. He explains how to inject the git SHA-1 hash sum into the maven ${buildNumber} variable. Then he lists a few ways in which this variable can be propagated in the build (e.g. manifest entry, property file, static method call, etc.). I am not going to repeat any of these implementations here - you can check out the "Advertise the Build Number" section of his post. Just would like to add to his list another implementation which I decided to use in this particular case:

Injecting the git revision in a VM parameter for the maven surefire plugin

The Junit tests are run by the maven surefire plugin. It spawns its own java VM and you can pass a custom parameter to the VM of the form The "trick" is to link the ${buildNumber} variable to the VM parameter. This can be done in the pom.xml in this way:

The VM parameter than can be read from the JUnit tests at execution time:


That's it. For completeness' sake I am listing below my entire pom.xml: