Wednesday, February 19, 2014

Ant execute actions based on if else conditions for an environment variable

Sometimes you may need to take different actions during your Java application build process depending on if an environment variable is set. A scenario that I came across is that if a particular environment variable was set, then files needed to be copied from one location, otherwise from another. Apache Ant is not meant to be a programming language so it is often difficult to accomplish tasks like this. However, I found a way to do this by creating two sub-targets for each boolean value of a conditional. Each target is conditionally executed by using if and unless attributes which check the property if the environment variable VARIABLE was set.
<property environment="env"/>

<condition property="exists.envVar">
    <isset property="env.VARIABLE"/>
</condition>

<target name="task" depends="-task-true, -task-false"/>

<target name="-task-true" if="exists.envVar">
    <echo>Execute something here</echo>
</target>

<target name="-task-false" unless="exists.envVar">
    <echo>Or execute this instead</echo>
</target>
The sub-targets are prepended with - character and are missing documentation attribute so that they cannot be executed from the command line. The user calls the main target (task in this example), and the logic does the rest.

No comments:

Post a Comment