2008-02-05

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} ." />
    </exec>
    <xmlproperty file="${tmpfilename}" prefix="svnprops"/>
    <delete file="${tmpfilename}" failonerror="false" />
    <echo>REV IS: ${svnprops.info.entry(revision)}</echo>
</target>

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"?>
<info>
<entry
kind="dir"
path="."
revision="8617">
<url>svn://server/svn/repo/trunk</url>
<repository>
<root>svn://server/svn/repo</root>
<uuid>6e0d6cc3-672d-0410-8be7-bcd0fe73158e</uuid>
</repository>
<wc-info>
<schedule>normal</schedule>
</wc-info>
<commit
revision="8617">
<author>jpdaigle</author>
<date>2008-02-05T21:08:30.585592Z</date>
</commit>
</entry>
</info>



 



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

2 comments:

Anonymous 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;
try
{
tr = new StreamReader(HttpContext.Current.Server.MapPath("~/.svn/entries"));
tr.ReadLine();
tr.ReadLine();
tr.ReadLine();
v = tr.ReadLine();
}
catch (Exception ex)
{
Logger.Error("Unable to read SVN revision number", ex);
v = "0";
}
finally
{
if (tr!=null)
tr.Close();
}
return "r" + v;
}

Anonymous said...

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