Location: JWare Software » AntXtras » Documents » How Tos » If-Then
If-Then
Q: How do I implement an if-then?
Conditional task execution is one of the features Ant users often cite as missing from a standard Ant installation. AntXtras supports three flavors of conditional execution: <do> (the workhorse), <domatch>, and <dowhile>. You need to use the <do> task to implement the simple “if-then” branch pattern.
Standard if/unless switches
The simplest test for a conditional branch is whether a standard Ant property exists or not. This test is virtually identical to the if/unless test you can associate with an Ant target. If you use the ‘if’ option, the nested tasks are executed if and only if the property exists (note that the property doesn’t have to be valid; for example, it can be unresolved). If you use the ‘unless’ option, the nested tasks are executed if and only if the property does not exist.
<do if="reports.enabled"> <generate-reports outputs="${reports.d}"/> </do> … <uptodate property="docs.uptodate".../> <do unless="docs.uptodate"> <generate-apidocs outputs="${docs.d}/apis"/> </do>
Extended if/unless switches
AntXtras includes a collection of if/else extensions that simplify testing more than one property in one go as well as testing of fixture elements other than properties (for example, AntXtras variables). Read the AntXtras User Guide for the complete list of if/unless switches.
<do unlessTrue="tests.disabled"> <run-programmertests reports="${reports.d}/junit"/> </do> … <do ifAllTrue="scrub.enabled,stats.enabled"> <truncatefiles haltiferror="no"> <files dir="${logs.d}"> <include name="*.status"/> <include name="*.last"/> </files> </truncatefiles> </do>
Of course you can combine if/unless switches; however you can specify only one instance of a particular switch…so you cannot specify two ‘if’ switches for example.
<do if="publish.testJars" unless="offline" unlessTrue="tests.disable"> [make jars of our programmer tests too] </do>
Platform switches
AntXtras also includes a few tests for checking the active Java and/or Ant runtime version. Read the AntXtras User Guide for the complete list of platform switches.
<do ifAntLike="1\.[6-8]+.*"> [do 1.6 or newer things...] </do> … <do ifOs="unix,*,SunOS"> [do unix solaris things...] </do> … <do ifJava="1.6+"> [do Java6 things...] </do>
Boolean Function Shortcuts
Finally, you can also use AntXtra’s extensive collection of condition function shortcuts with the <do> task’s ‘true’ and ‘false’ switches.
<do true="${$filenotempty:${setup.properties}}"> [do something with setup properties] </do> … <do false="${$weekday:}" true="${$nightslot:${TSTAMP}}"> [do batch batch batch] </do>