Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Essential Groovy DSLs


[ 36 ]

If we add multiple doFirst and doLast actions in a task, Gradle gives us what seem
to be illogical results. So, the first doFirst action is last and the last doLast action is
last to be executed. Confused? Look at this task and then check out the output, and it
will be clearer:


task confused {
doFirst {
println "The First doFirst will be last"
}
doFirst {
println "The last doFirst will be first"
}
doLast {
println "The first doLast will be first"
}
doLast {
println "The last doLast will be last"
}
}

You can execute the preceding task from the root directory of the sample code
package with the following command:


$gradle -q -b scripts/ChapterThree/hello.gradle confused


The last doFirst will be first


The First doFirst will be last


The first doLast will be first


The last doLast will be last


From the preceding output, we can see that the order of our actions is not quite
what we might have expected. The reason is that each of the doFirst and doLast
methods are executed in turn as they occur in the task definition. When Gradle
encounters a doFirst method in the definition, it is established as the first action to
execute, but subsequent doFirst actions are inserted before it. The same happens
with doLast, except that doLast at least adds actions to the action list in the order
they are encountered.


For the preceding reasons and to avoid hours spent scratching your head wondering
why actions are not performing in the order you expect, I suggest not using doFirst
and doLast in anything except a trivial Gradle task. The better notation to use is the
<< operator as follows:


task helloSimple << {
println "Hello, Simple World!"
}

http://www.ebook3000.com
Free download pdf