Wednesday, June 10, 2009

Gant Helper

Using Gant for build scripts is pretty cool because it is a lightweight facade over Ant. You can do anything you can do in Ant by converting the syntax, but also mix in Groovy code. Using Groovy to script means better reuse of code and shorter build scripts. To learn more about Gant, read this page: http://gant.codehaus.org/

For those of you familiar with Gant, I have created a few helper closures at the top of my script that you may find useful.

includeTool << env = { 
variable -> return System.getenv()[variable] }
prop = { propKey -> return ant.project.properties[propKey] }
log = { target -> println "\n[${target.name}] ${target.description}" }
run = { command -> def out = ""; execute.shell(command, outProcessing:{out+=it+"\n"}); return out}

"env" - shortcut to reading environment variables. Example:

buildNumber = env('BUILD_NUMBER')

"prop" - shortcut to reading properties that were loaded into ant. Example:

appName = prop.'application.name' //If you know Groovy, you know it could also be: prop('application.name')

"log" - By default, Gant won't print the targets as they are executed. You get the Ant task prints, but this is helpful when you use "depends" and want to follow the script. Just use "log(it)" or "log it" at the top of each target in you script. Example:

target(compile: 'Compile everything') {
log(it)
ant.groovyc( ... )
}

Prints:

[compile] Compile everything
[groovyc] Compiling 1 source file
It can also be used for methods by manually passing the "it" object:
def junit() {
log([name:'junit', description:'Runs all JUnit Tests'])
}

"run" - executes a shell command and also returns the output. Example:

def svnlogOut = run("svn info")
println svnlogOut

2 comments:

  1. Thanks!
    Looks like the code didn't paste into your blog correctly.
    Should the env command look like this?
    env = {variable -> return System.getenv()[variable] }

    ReplyDelete
  2. 5 years later saw this comment... fixed the code (that probably nobody's using now). thank you.

    ReplyDelete