Plugin - read value from extension and configure task dependencies

I have a use case that based on the boolean value from the plugin extension I set up dependency between javaCompile and my custom task.

pseudocode

// Plugin class
@Override
public void apply(Project project) {
  CustomExtension customExtension = project.getExtensions().create("customExtension", CustomExtension.class);
  ...
  project.afterEvaluate(currentProject -> {
      if (customExtension.isAutoRegisterTasks()) {
        currentProject.getTasks().getByName("compileJava").dependsOn(CUSTOM_TASK_NAME);
      }
  });
}

is there a way that I can set up task dependencies based on the value of the plugin extension without relying on afterEvaluate? As I have to deal with some workarounds with it in testing and also in generally you propose to avoid it.
I didn’t find obvious solution.

Closest reference I could find it here → Querying Gradle extension properties when applying the extension - Help/Discuss - Gradle Forums from 2015 :upside_down_face:

Going one step back and not answering your question directly.

afterEvaluate is not the only bad practice you have there.

By using getByName for example you break task-configuration avoidance.

Also, any explicit dependsOn that does not have a lifecycle task on the left-hand side is a code smell,
as usually you should instead wire outputs to inputs and thus get necessary task dependencies automatically.

Why for example does the compileJava task need to depend on CUSTOM_TASK_NAME?
Does CUSTOM_TASK_NAME generate Java sources that compileJava then should compile along?
If so, just instead do sourceSets { main { java { srcDir(tasks.named(CUSTOM_TASK_NAME)) } } } then all tasks that need sources automatically get those generated sources and the necessary task dependency and you also do no need to manually configure the compileJava task or similar. Just make sure CUSTOM_TASK_NAME properly declares its inputs and outputs as usual.

Regarding reacting to the boolean in the extension it depends on many factors.
You could for example simply have an onlyIf in CUSTOM_TASK_NAME that just skips the task execution if the boolean is not set and as it is evaluated at execution time, no afterEvaluate is necessary.

Or you could replace the boolean property with a function in the extension and if the function is called, then do the respective configuration that you would do if the boolean was set to true.

1 Like