Sunday, January 24, 2016

Gradle Tasks Example Execution

The following is a build.gradle which is what's executed when you run gradle <tasks>

task a << {  //double left angle brackets are the same as "doLast" or  more technically the "leftShift" operator
 println "in a"
}
  task b {
 println "in b"
}
  task (c, type: Copy) {
 from('c:/tmp/from/')
 into('c:/tmp/to')  
}
  c << {
 println "in c" //this ("in c") does not print below during the configuration phase for the same reason a doesn't: the print statement is in an action closure (added via leftShift op) unlike the print statements in b,d, and f whose print statements are executed as part of the configuration phase. Moreover, the "in c" is not printed in the execution phase. Why? because Gradle considers it doesn't have any work to do (hence the "UP-TO-DATE") output. If there was a file in c:/tmp/from/ then "in c" would be printed so I guess Gradle determines "didWork" property from the Copy type and ignores the leftShift appended print task here.
}
  task (d, type: Copy) {
 println "in d"
}
task e {
 doLast {
  println "in e"
 }
}
task f {
 println "in f"
 doLast {
  taskname -> println "in $taskname doLast" //note groovy (pun intended) use of lambdas.
 }
}
task g(dependsOn: c) << {
 println "c did work: " + c.getState().getDidWork();
 println "c.destinationDir: " + c.destinationDir
}
task h(dependsOn: b) << {
 println "b did work: " + b.getState().getDidWork();
}
task i(dependsOn: a) << {
 println "a did work: " + a.getState().getDidWork();
}
gradle.taskGraph.whenReady {taskGraph ->
    println "c is set to execute: " + taskGraph.hasTask(c)
}
println "the end of configuration phase"

executed:
>gradle a b c d e f g h i
in b
in d
in f
the end of configuration phase
c is set to execute: true
:a
in a
:b UP-TO-DATE
:c UP-TO-DATE
:d UP-TO-DATE
:e
in e
:f
in task ':f' doLast  // note the output from a, e, and f but none from c for reasons stated above.
:g
c did work: false
c.destinationDir: C:\tmp\to
:h
b did work: false
:i
a did work: true

BUILD SUCCESSFUL

Total time: 3.222 secs
ref: https://discuss.gradle.org/t/how-to-understand-task-creation-syntax/4478
see also: https://docs.gradle.org/current/userguide/build_lifecycle.html

No comments:

Post a Comment