Tuesday, February 24, 2009

1.2.3... lets get Nant to respect ANT's error codes

If you've ever struggled to get a NANT build to 'fail' when calling through to ANT via ANT's ant.bat file (which fails to return the error-code seemingly), hopefully the following snippet will help you. This is a snippet of NANT executing a target on an ANT build file.

<target name="nant-target">
<!-- The impressively confusing jumping through hoops of re-directing the ant.bat's standard out to a file and then reading that file back in
is to get around the fact that the ant.bat file always returns '0' even when the build.xml file has 'failed' *sob* -->
<property name="ant_results_file" value="ant_result.txt"/>
<delete file="${ant_results_file}" />
<exec program="${environment::get-variable('ANT_HOME')}\bin\ant.bat"
output="${ant_results_file}"
append="true"
commandline="-buildfile antfile.xml anttarget" />
<loadfile file="${ant_results_file}" property="ant_result" />
<!-- For those voyagers coming this way in the future, we're looking for either a BUILD FAILED or a BUILD SUCCEEDED, that rather crucially
is the *LAST* one in the file -->
<regex pattern="(?'build_status'BUILD (FAILED|SUCCEEDED))(?!.*BUILD (FAILED|SUCCEEDED)).*$"
input="${ant_result}"
options="Singleline"/>
<delete file="${ant_results_file}" />
<if test="${build_status == 'BUILD FAILED'}">
<fail message="ANT target failed"/>
</if>
</target>