Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 3

[ 35 ]

Gradle tasks


As we saw previously, Gradle tasks are the building blocks of a Gradle build. We can
define as many tasks as we like within our build script. Here is an example of a very
simple task:


task hello {
doLast {
println "Hello, World!"
}
}

What the preceding Gradle script snippet is doing is declaring a single task called
hello. Tasks can be comprised of multiple actions. In this case, there is one action
defined for the task, that is, the code block:


{
println "Hello, World!"
}

This is actually a Groovy closure. We will dedicate a full chapter later to learning
about closures. It is sufficient for now to know that by declaring this as the doLast
action we are asking for this block of code to be executed last as part of the hello
task. You can run this script from the command line as follows:


$gradle -q -b hello.gradle hello


For the rest of the Gradle examples in this chapter, we will always use the
-q "quite execution" option. This will ensure that only the output from the
tasks is printed and not the other Gradle status messages on startup.

Adding actions to tasks

There is also a doFirst method we can use to add an action to the start of a task.
The doFirst and doLast methods are useful notational conveniences if you have
a very simple task to define like the one that follows:


task helloWithActions {
doFirst {
print "Hello, "
}
doLast {
println "World Actions!"
}
}
Free download pdf