Conditional tasks in Ant

If you’re using Ant build scripts, there is a good chance that you will want to do some tasks conditionally – for example, if you’re using CI you will want to run your unit tests every time some code is committed – but you might only want to regenerate documentation or update a stakeholders’ preview build every night.

There is a lot of talk about conditional tags, but all these really allow you to do is set even more variables. You can use if/then/else from Ant-Contrib but that involves adding extra libraries and complicating the issue.

Actually, it turns out it is really simple to set up conditional tasks in your build process. All you need to do is call the task, but in the task header use the if attribute.

For example, I have a build task which calls all the other tasks.

<target name="build" depends="clean,checkout,nightly,phpunit,documentation" />

Even though I’m running this every time, I’m calling the “nighty” task. Below shows how I define that.

<target name="nightly" if="${env.NIGHTLY}">

Finally, in my Jenkins CI install, I make the project a parameterised build, and add a boolean called NIGHTLY that defaults to false. I can then also trigger a build by cron that specifies the NIGHTLY parameter as true, so that when it runs on a night, it runs the additional tasks as well.

Timeline

Newsletter

Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.

Metadata

Tags: , , , , , ,

This entry was posted on Thursday, February 28th, 2013 at 10:15 am and is filed under Programming, Tech. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.