Jul 17, 2010

Conditional execution in ant

An ant target can be configured to execute conditionally using if and unless attributes available.
A simple ant target without any attributes

<project name="examples" default="simple_target_example">

  <target name="simple_target_example">
    <echo message="a simple target example"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

simple_target_example:
     [echo] a simple target example

BUILD SUCCESSFUL
Total time: 0 seconds

Ant target with an if attribute
<project name="examples" default="example_if_target">

  <target name="property_target">
    <property name="greetings" value="1"/>
  </target>

  <target name="example_if_target" depends="property_target" if="greetings">
    <echo message="Greetings"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

property_target:

example_if_target:
[echo] Greetings

BUILD SUCCESSFUL
Total time: 0 seconds

The if="greetings" attribute causes the target to be executed if greetings property is set and the unless="greetings" attribute causes the target to be executed only if the property greetings is not set

Ant target with an unless attribute
<project name="examples" default="example_unless_target">

  <target name="example_unless_target" unless="greetings">
    <echo message="Greetings"/>
  </target>

</project>
Output
$ ant
Buildfile: build.xml

example_unless_target:
[echo] Greetings

BUILD SUCCESSFUL
Total time: 0 seconds


//setting the greetings property
Output
$ ant -Dgreetings=1
Buildfile: build.xml
 

example_unless_target:
BUILD SUCCESSFUL
Total time: 0 seconds

No comments :

Post a Comment