Writing custom tasks in Gradle is very easy if we understand the lifecycle of its execution https://docs.gradle.org/current/userguide/build_lifecycle.html
Sample custom tasks from build.gradle file
Copy of the build.gradle available in https://github.com/venkatesh-mohanram/gradle-experiments/blob/master/gradle-custom-tasks/build.gradle
Execution of the custom task will result in the following output; if we notice the first execution all are the initialization code, followed by the execution phase. Within execution, it executes in the following order doFirst, class method and finally doLast
Sample custom tasks from build.gradle file
Copy of the build.gradle available in https://github.com/venkatesh-mohanram/gradle-experiments/blob/master/gradle-custom-tasks/build.gradle
class CustomParentTask extends DefaultTask {
String cv_var1
@TaskAction
void build() {
println "CustomParentTask:build() $cv_var1"
cv_var1 = "CHANGE IN BUILD"
}
}
task customParent(type: CustomParentTask) {
// Initialization
customParent.ext.var1 = 'INITIAL'
cv_var1 = customParent.ext.var1
println "customParent:Initialization"
// Execution
// doFirst -> build() -> doLast
doFirst {
custom.var1 = 'hello'
customParent.ext.var1 = 'World'
cv_var1 = customParent.ext.var1
println "customParent:doFirst"
}
doLast {
println "customParent:doLast"
}
}
class CustomTask extends DefaultTask {
@TaskAction
void build() {
println "CustomTask:build()"
}
}
task custom(type: CustomTask, dependsOn: customParent) {
// Initialization
custom.ext.var1 = ''
println "custom:Initialization"
// Execution
// doFirst -> build() -> doLast
doFirst {
println "custom:doFirst $custom.ext.var1 $customParent.var1"
}
doLast {
println "custom:doLast"
}
}
Execution of the custom task will result in the following output; if we notice the first execution all are the initialization code, followed by the execution phase. Within execution, it executes in the following order doFirst, class method and finally doLast
$ gradle custom
> Configure project :
customParent:Initialization
custom:Initialization
> Task :customParent
customParent:doFirst
CustomParentTask:build() World
customParent:doLast
> Task :custom
custom:doFirst hello World
CustomTask:build()
custom:doLast
BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed
No comments:
Post a Comment