Thank you for the help!
The only potential concern is that this code will run before the configuration added when the task is registered
I guess it depends what one wants to configure. I was only looking to add dependsOn
and mustRunAfter
s so whenTaskAdded
/withType
would work, but I’ve had problems in the past when I needed to alter task configuration state after the initial configuration has been done.
Otherwise it became convoluted quick, but it works now mostly after about 10 iterations of tries:
println("configuring build")
println("registering bar")
tasks.register("bar") {
println("configuring bar")
}
configureTaskForSureAfterInitialConfiguration(project, "bar", DefaultTask) {
println("configuring bar after register")
}
configureTaskForSureAfterInitialConfiguration(project, "foo", DefaultTask) {
println("configuring foo before register")
}
afterEvaluate {
configureTaskForSureAfterInitialConfiguration(project, "foo", DefaultTask) {
println("configuring foo in afterEvaluate before register")
}
configureTaskForSureAfterInitialConfiguration(project, "bar", DefaultTask) {
println("configuring bar in afterEvaluate after register")
}
}
afterEvaluate {
println("registering foo")
tasks.register("foo") {
println("configuring foo")
}
}
afterEvaluate {
configureTaskForSureAfterInitialConfiguration(project, "foo", DefaultTask) {
println("configuring foo in afterEvaluate after register")
}
}
static void configureTaskForSureAfterInitialConfiguration(
Project project, String name, Class taskType, Action<? super Project> configure
) {
project.tasks.withType(taskType) {
if (it.name == name) {
project.afterEvaluate {
project.tasks.named(name).configure(configure)
}
}
}
}
tasks.register("dummy")
> Configure project :
configuring build
registering bar
configuring bar
configuring bar after register
registering foo
configuring foo
configuring bar in afterEvaluate after register
configuring foo before register
configuring foo in afterEvaluate before register
configuring foo in afterEvaluate after register
This works everywhere by running after the initial configuration. Even if it is called after register
which doesn’t work with whenTaskAdded
/withType
(this part wasn’t in OP). configureTaskForSureAfterInitialConfiguration
seems to be a good way of making sure the task is configured correctly, even if the implementation detail of when the task created is changed inside the plugin declaring foo
.
Now, there’s only one interesting issue, foo
and bar
get configured even when I’m not executing them: gradle dummy
I thought that using
register
/named
would result in lazy configuration.