Building task name based on extension property value


(Benjamin Muschko) #1

Assume I’d like to create a new task in a plugin. The name of task is built dynamically based on the value of an extension provided by the plugin.

The following code describes what I do in the plugin:

class MyExtension {
    String name
}
  project.extensions.create('custom', MyExtension)
  project.task("${project.custom.name}Task")

In the build script that applies the plugin, I set the value of property exposed by the extension:

apply plugin: 'myPlugin'
  custom {
    name = 'test1'
}

Without wrapping the task creation code into an afterEvaluate block, the extension property value will be null. This makes sense as the extension is not evaluated yet. Is there a different/better way to achieve this without using afterEvaluate. Alternatively, is there a way to delay setting the task name?

Thanks,

Ben


(Luke Daley) #2

There’s no way to defer it.

We are trialling an idea for deferring configuration more generally in 1.5 on with the publishing extension. Look at @DeferredConfigurable in the codebase and its uses. This is an incubating feature though.

I can’t offer any other advice without knowing more about the use case.


(Benjamin Muschko) #3

I just had a look at the DeferredConfigurableExtensionIntegrationTest. Looks like a promising approach. I will need to play around with it over the weekend.

My concrete use case can be found in this plugin class. If you have a look at the code you will find that a property value of the extension is used to build the task name. In order to make sure the extension is evaluate the task creation code is wrapped with project.afterEvaluate.


(Luke Daley) #4

There’s also a discussion on this general naming problem going on here: http://gradle.1045684.n5.nabble.com/polymorphic-containers-td5711301.html