Conditional Task on exec failure in Ant

2020-02-01 06:12发布

问题:

I have some unit tests running through Ant, and I'd like to be able to run some cleanup code if the unit tests fail. I was looking for some sort of "finally" block, but I had no luck finding one. I've tried using errorproperty and if statements on tasks, but ant only accepts "true", "on" and "yes" as true properties. A successfully executed task (on unix at least) returns 0, so I've had to construct a ridiculously elaborate apparatus:

<project name="TestBuild" default="build" basedir=".">
<target name="build" depends="truth,checkresult,cleanup" />

<target name="truth">
    <echo message="Running Truth" />
    <exec executable="false" errorproperty="testfailure"/>
</target>
<target name="checkresult">
    <condition property="testfailed">
        <not>
            <equals arg1="${testfailure}" arg2="0" />
        </not>
    </condition>
</target>
<target name="cleanup" if="testfailed">
    <echo message="cleanup" />
    <fail />
</target>

Is there any simpler way to do this? For one, this requires to tasks to complete, which seems ridiculous. It also means I'd have to call both of them after every block of unit tests, because I obviously can't set failonerror as I normally would. In all, it's a hacky, inelegant solution, and I'm hoping someone has better one.

回答1:

Two possiblities

-1-
use some try/catch/finally construct for specific parts of your script
you need some Ant Plugin that provides those features, f.e. =

Flaka
Antcontrib / Antelope

    <trycatch>
     <try>
      <exec .../>
     </try>
     <catch>
      do your cleanup here
      and afterwards don't forget to fail
      </fail message="......."/>
     </catch>
      optionally you may use a finally section also
     <finally>
      ..
     </finally>
   </trycatch>

-2-
use a buildlistener for the whole script ( BUILD SUCCESSFUL, BUILD FAILED )

Kev Jackson has a nice example of an exec-listener in his presentation, = http://people.apache.org/~kevj/ossummit/extending-ant.html (the sources of the exec-listener are included in the slides)

You're able to kick off specific tasks depending on the build result after your build has finished

<!-- taskcontainer -->    
<exec-listener onSuccess="true|false">
..

 your stuff goes here 
..
</exec-listener>


回答2:

Ant contrib has the concept of a try-catch-finally. However this is a finally for a particular block, not for the entire script.