loosebazooka
loosebazooka

Reputation: 2433

Conditionally add task to task tree in gradle

I have a Gradle plugin with some conventions for configuration.

myplugin {
  doSomethingOnBuild = true/false
}

In the plugin source, I'm using the doSomethingOnBuild to conditionally add a task (postProcessTask) to the task tree. The reason the task is conditional is that the postProcessTask is only necessary for builds of a certain type.

projects.gradle.projectsEvaluated {
  if(convention.doSomethingOnBuild == true) {
    // add postProcessTask to tree using dependsOn
  }
}

I feel weird about using doSomethingOnBuild because I need to wrap it in a project.gradle.projectsEvaluated to have the convention parameter available in the configuration phase, and also gradle is warning me about dynamic property use (which is deprecated)

Is there a better way to do this? Should I not be doing this at all? Is it up to the user to invoke the postProcessTask?

Upvotes: 0

Views: 967

Answers (1)

Peter Niederwieser
Peter Niederwieser

Reputation: 123996

It's not all too common to add tasks conditionally, but without having more context, I can't say whether I'd go for this or another solution (add a description and group for the task, split into multiple plugins, etc.). In any case, it's normal, and oftentimes mandatory, for a plugin to defer access to the build model, and gradle.projectsEvaluated is indeed one way to do so.

Regarding the warning about "Creating properties on demand", it means that someone is setting a property named doSomethingOnBuild on the :Test project, although no such property was declared. This might hint at a problem with the plugin, or perhaps someone tried to set the property before applying the plugin.

In case you are referring to convention objects in the strict Gradle sense, note that they have been largely replaced by extension objects. You can learn more about extensions in the Gradle User Guide. (This doesn't explain the deprecation warning, though.)

Upvotes: 1

Related Questions