Use of "whenTaskAdded" breaks configuration check in custom task

Hi all,

I have a task which checks its configuration when configure is invoked. The idea is to throw an exception in case the user missed to set certain parameters.

As soon as I use tasks.whenTaskAdded this mechanism breaks dependent on the order of appearance. If it comes before the task definition the config closure is not evaluated. If it comes after, it is.

Is it okay that this config closure is applied at different times? I would expect no difference in behavior since it introduces dependencies between plugins/scripts. Or am I doing something wrong?

Example script:

build.gradle

class MyBaseTask extends DefaultTask {
public String Text = null;

@Override
public Task configure(Closure cl) {

final Task task = super.configure(cl)

if (Text != null) {
  println "Task configured, fine!"
}
else {
  throw new GradleException("Task not configured!")
}

}
}

buildscript {
}

// if ‘whenTaskAdded’ is moved here we get an exception

task MyTask(type: MyBaseTask) {
Text = “Hello World!”
}

// having ‘whenTaskAdded’ here is fine; if we move it up the config check fails
tasks.whenTaskAdded { addedTask ->
println "Just added task: " + addedTask.name
}

Thank you,
Heiko

The configure method is not part of the public API and not meant to be overwritten.

For validation you can either use Gradle.taskGraph.whenReady() (if it is important that the validation is done before any task runs) or just do the validation as part of your task’s action.

1 Like