Archive for May, 2009

Generating ANT build numbers using subversion

May 8, 2009

I have been working on a Java project recently where we are using ANT as a build tool and Subversion for version control. Managing software build-versions manually is bothersome and the ANT’s build-in buildnumber task has many problems/pitfalls.

Using subversion and it’s reversion history is really the way to go for easily generating consistent, ’build’ numbers across team member machines. Furthermore, if your application has multiple modules (in multiple directories) subversion can easily provide individual version numbers for each module.

Unfortunately, subversion is poorly supported by ANT. There are many optional add-on tasks that can be downloaded, but all the ones that I looked at either did not work, was not portable or the license was unacceptable.

The best solution I could find was to invoke the subversion command line command “svnversion” directly from ANT and with a little help from here and here, I wrote a nice little macro that can be used from ANT 1.6+.

<macrodef name="svnversion" description="Get last subversion commit version.">
 <attribute name="dir"/>
 <attribute name="outputproperty"/>
 <attribute name="unversionedDefault"/>
 <sequential>
  <echo message="svnversion -n -c '@{dir}' => '@{outputproperty}'"/>
  <exec outputproperty="@{outputproperty}" executable="svnversion" failonerror="true">
  <arg line="-n -c @{dir}" />
  <redirector>
   <outputfilterchain>
   <tokenfilter>
    <replaceregex pattern="^[0-9]*:" replace="" flags="g"/>
    <replaceregex pattern="exported" replace="@{unversionedDefault}" flags="g"/>
   </tokenfilter>
   </outputfilterchain>
  </redirector>
  </exec>
  <echo message="svnversion returned '${@{outputproperty}}'"/>
 </sequential>
</macrodef>

Usage example

<!--
Sets the ant propery 'src_revision' the the subversion revision of the 'src' directory.
-->
<svnversion unversionedDefault="" dir="src" outputproperty="src_revision"/>

P.S. The last echo statement in the ANT macro also demonstrates a useful ANT trick: How to get the indirect value of a property using another property’s value as the name of the property that we are retriving the value from? This is something that is only possible in ANT 1.6 using macros.


Design a site like this with WordPress.com
Get started