While you can certainly just throw an exception in a scriptdef to stop an Ant script that is using a scriptdef, perhaps it is best to use Ant’s Exit task. This allows Ant to do whatever it has to do as it handles the resulting BuildException.
The exit task is used in an Ant script as “fail”. To use ‘fail’ in a scriptdef you just use the predefined ‘self’ variable that references the scriptdef instance. This is illustrated in listing 1 below.
An alternative to the scriptdef ant task is to use the ‘groovy’ task that comes with the Groovy environment. This is perhaps the simplest approach when you don’t need the full structure that the scriptdef task makes available to a script. The scriptdef task allows one to pass in Ant XML elements and attributes.
<project name="example" default="demo"> <!-- reference the groovy libs --> <path id= "libs" > <fileset dir= "../lib"> <include name="groovy/groovy-all-1.8.6.jar" /> </fileset> </path> <!-- An inline scriptdef that throws an exception --> <scriptdef name="solveProblem" language="Groovy" classpathref="libs"> self.fail("intentionally failed") </scriptdef> <!-- a call of the scriptdef --> <target name="demo"> <solveProblem/> </target> </project>
A run …
>ant -f fail.xml Buildfile: fail.xml demo: BUILD FAILED fail.xml:15: intentionally failed Total time: 1 second
- BuildListener using Groovy In Ant Scriptdef
- Notes on using Groovy in Ant Scriptdef
- Groovy AntBuilder in Ant Scriptdef to Replace Props
- Extend a Groovy Scriptdef with inline task
- Ant hooks using Groovy scripts via Scriptdef