Ant Tricks: how to find the SVN revision of a directory with Ant

Here's a neat little recipe I wrote when trying to get the current SVN revision of a checked-out project into an Ant property.

Why would you need to do this?

Well, for example, you might want Ant to get the revision number of the source going into the build it's making and use it to name the output directory it creates when deploying your load. (ie: deploy the built library to /projects/myproject/build_svnXXXX/) You might also want to echo that revision number into some resource file to implement a "--version" type of command line option in your application, etc.

Sample Ant Target

<target name="load-svn-revinfo" depends="init-stage1">
    <property name="tmpfilename" value="tmpout.txt" />
    <delete file="${tmpfilename}" failonerror="false" />
    <exec executable="svn" dir="${basedir}/../" output="${tmpfilename}">
    <arg line="info --xml --username ${svn.username} --password ${svn.password} ." />
    <xmlproperty file="${tmpfilename}" prefix="svnprops"/>
    <delete file="${tmpfilename}" failonerror="false" />
    <echo>REV IS: ${svnprops.info.entry(revision)}</echo>

How it Works

There are basically three steps:

  1. Run an "svn info --xml" on your project sandbox and store the result to a temp file.
  2. Load the temp file into an Ant <xmlproperty/>, with the prefix "svnprops", so we can refer to the revision later in our build script.
  3. Clean up the temp file.

Note that running "svn info --xml ." on your checkout directory will give you output like this:

C:\dev\eclipse_workspace\HEAD_solsuite>svn info --xml .
<?xml version="1.0"?>


Meaning that once that's loaded with <xmlproperty/>, we can refer to the SVN revision as ${svnprops.info.entry(revision)}. Pretty cool, huh?


jkealey said...

In our ASP.NET app, we don't have access to the svn executable (as it is not installed on the web server).

We went with this lazy hack...

public static string getSvnRevision()

String v;
TextReader tr=null;
tr = new StreamReader(HttpContext.Current.Server.MapPath("~/.svn/entries"));
v = tr.ReadLine();
catch (Exception ex)
Logger.Error("Unable to read SVN revision number", ex);
v = "0";
if (tr!=null)
return "r" + v;

Anonymous said...

Thanks for this posting! It is much better than hacking regex.