Setting a build version in a JAR file from TFS build

Whilst helping a Java based team (part of larger organisation that used many sets of both Microsoft and non-Microsoft tools) to migrate from Subversion to TFS I had to tackle their Jenkins/Ant based builds.

They could have stayed on Jenkins and switched to the TFS source provider, but they wanted to at least look at how TFS build would better allow them to  trace their builds against TFS work items.

All went well, we setup a build controller and agent specifically for their team and installed Java onto it as well the TFS build extensions. We were very quickly able to get our test Java project building on the new build system.

One feature that their old Ant scripts used was to store the build name/number into the Manifest of any JAR files created, a good plan as it is always good to know where something came from.

When asked as how to do this with TFS build I thought ‘no problem I will just use TFS build environment variable’ and add something like the following

1<property environment="env"/> 
2
3<target name="jar">  
4        <jar destfile="${basedir}/javasample.jar" basedir="${basedir}/bin">  
5            <manifest>  
6                <attribute name="Implementation-Version" value="${env.TF\_BUILD\_BUILDNUMBER}" />  
7            </manifest>      
8        </jar>  
9</target>

But this did not work, I just saw the text ${env.TF_BUILD_BUILDNUMBER}" in my manifest, basically the environment variable could not be resolved.

After a bit more of think I realised the problem is that the Ant/Maven build extensions for TFS are based on TFS 2008 style builds, the build environment variables are a TFS 2012 and later feature, so of course they are not set.

A quick look in the automatically generated TFSBuild.proj file generated for the build showed that the MSBuild $(BuildNumber) was passed into the Ant script as a property, so it could be referenced in the Ant Jar target (note the brackets change from () to {})

1
2
3<target name="jar">  
4        <jar destfile="${basedir}/javasmaple.jar" basedir="${basedir}/bin">  
5            <manifest>  
6                <attribute name="Implementation-Version" value="${BuildNumber}" />  
7            </manifest>      
8        </jar>  
9</target>

Once this change was made I then got the manifest I expected including the build number

1Manifest-Version: 1.0  
2Ant-Version: Apache Ant 1.9.4  
3Created-By: 1.8.0\_25-b18 (Oracle Corporation)  
4Implementation-Version: JavaSample.Ant.Manual\_20141216.7