I have a gradle task which runs some code checks, which is usually executed during build. Since this tasks takes a long time, I implemented a flag so that it is not run during normal build, but needs to be enabled via a property:
tasks.withType(MyTaskType) {
//config switch "-Pcheck=true"
enabled = project.getProperties().getOrDefault('check', false).equals('true')
}
Now I can start it in the terminal via: ./gradlew build -Pcheck=true
Now I also want to have a task "buildWithCheck", which sets this property and then executes the build task.
How can I do this? What I tried:
task buildWithCheck {
doFirst{
project.getProperties().put('check','true')
}
dependsOn tasks['build']
}
Task enabled
is evaluated very early in the DAG creation so cannot be overridden by other tasks. What you want is the onlyIf
condition. Below code allows checks to be run either way:
gradle test -Pcheck=true
gradle testSlowly
build.gradle:
ext {
check = project.properties['check'] ?: "false"
}
task test {
onlyIf { project.ext.check == "true" }
doLast {
println "TEST"
}
}
task testSlowly {
doFirst{ project.ext.check = "true" }
finalizedBy 'test'
}
build.gradle.kts (for kicks, I tried doing this in Kotlin too)
var check: String by extra { properties.getOrDefault("check", "false") as String }
tasks {
val test by registering {
onlyIf { check == "true" }
doLast {
println("TEST")
}
}
register("testSlowly") {
doFirst { check = "true" }
finalizedBy(test)
}
}