There are some kind of tasks, which Ant won’t do. One of them is the loop. There is no simple way to implement a dynamic for or while loop in Ant. What do i mean with dynamic? Let me make an example. Ant reads out a number of iterations from a property file (we call it the number x) and should perform a loop x-times to call another Ant task. And this can only hardly be done with Ant.
But fortunately, there is Groovy. Groovy is a scripting language, which runs in a Java Virtual Machine. And because of that, it can be easily integrated with Ant.
- Download the latest release of Groovy at http://groovy.codehaus.org/Download
- Inside the Groovy binary, there is a folder called embeddable. In this folder, there is a file called groovy-all-X.X.X.jar. Take it and copy it near your build file.
- Create a task definition in Ant
<taskdef name="groovy" classpath="./groovy-all-X.X.X.jar" classname="org.codehaus.groovy.ant.Groovy" />
- Use Groovy somewhere inside an Ant task:
<groovy> int i = 1 int numberOfIterations = properties["numberOfIterations"].toInteger() while (i < = numberOfIterations) { properties["currentIteration"] = i ant.antcall(target:"execute.a.task") i++ } </groovy>
Isn’t that groovy?
Groovy integrated in Ant offers many possibilities, which can be read here http://groovy.codehaus.org/The+groovy+Ant+Task. I used for my little script the variable ant, an instance of the current Ant project and the properties map, which holds all properties inside Ant.
Hello Stefan,
Interesting. NAnt offers for example for loops specific tasks to do the job. With that you can even do complex foreach loops over csv files etc.
http://nant.sourceforge.net/release/latest/help/tasks/foreach.html
But unfortunately this is not as “almighty” as the possibility to execute groovy scripts. But NAnt offers the possibility to execute CSharp scripts directly in the NAnt script. You have there direct access to all namespaces in the .NET Framework. See http://nant.sourceforge.net/release/latest/help/tasks/script.html
Daniel
For Ant, there is also the Ant Contrib library, which offers the foreach possibility: http://ant-contrib.sourceforge.net/tasks/tasks/foreach.
But in my case, the foreach loop wasn’t useful. We needed a usual loop with a number of iterations. This number was calculated on runtime and was then used for the loop.