Showing posts with label ant. Show all posts
Showing posts with label ant. Show all posts

Running an Ant Script in Groovy



>> Wednesday, September 1, 2010

I recently wanted to test the execution of an Ant script and I wanted to use Groovy. There are a lot of blogs about using AntBuilder to run Ant tasks in Groovy, but that isn't what I needed. I actually needed to test the Ant script itself.

This was not to hard, but the concept is tricky. I used AntBuilder to execute an external process (using the exec task). In this case, the external process is ant. Lost yet? Here is the code, maybe that will make it easier:


File antExecutable = new File("C:/Ant/bin/ant.bat")
assert antExecutable.exists()

File antScript = new File("C:/antscripts/build.xml")
assert antScript.exists()

def ant = new AntBuilder()
ant.exec(executable: antExecutable.getAbsolutePath(),
outputproperty:"cmdOutput",
errorproperty:"cmdError"){
arg(value: "-f")
arg(path: antScript.getAbsolutePath())
}
assert ant.project.properties.cmdOutput.contains("BUILD SUCCESSFUL")
assert ant.project.properties.cmdError == ""


Hopefully this is pretty straight-forward. Basically this is equivalent to calling "ant -f C:\antscripts\build.xml" from a command line. If you want to know more about how to use AntBuilder, go here.

The output gets stored in a property called "cmdOutput" which can be tested using the "ant.project.properties.cmdOutput" variable. In a similiar way, the standard error gets stored in "cmdError." If you just want to display the output, remove the outputproperty and errorproperty from the exec task.

There are a couple other things you might need to do.

First, if you want to pass additional arguments to the script (for example, setting some ant properties), you can just add additional "arg" lines like this:


ant.exec(executable: antExecutable.getAbsolutePath(),
outputproperty:"cmdOutput",
errorproperty:"cmdError"){
arg(value: "-f")
arg(path: antScript.getAbsolutePath())
arg(value: "-DsomeProperty=someValue)
}


Second, if the ant script needs to know about some classpath variables, just add an "env" line like this:


ant.exec(executable: antExecutable.getAbsolutePath(),
outputproperty:"cmdOutput",
errorproperty:"cmdError"){
arg(value: "-f")
arg(path: antScript.getAbsolutePath())
env(key: "CLASSPATH", path: "C:/jars/;C:/project/files")
}


Leave a comment if you have any questions or suggestions

Read more...

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP