I tried to write a precompiled script plugin to learn how to use ListProperty
.
buildSrc/src/main/groovy/GreetingPlugin.gradle
:
abstract class GreetingPluginExtension {
abstract ListProperty<String> getUsers()
abstract Property<String> getOwner()
}
def extension = project.extensions.create('greeting', GreetingPluginExtension)
abstract class MyTask extends DefaultTask {
@Input
abstract Property<String> getUsername()
@TaskAction
def task_action() {
println "Hello "+username.get()+" !"
}
}
tasks.register("AllMyCustomTasks", DefaultTask) {
}
tasks.register("MyCustomTask_Owner", MyTask) {
username = extension.owner
}
AllMyCustomTasks.dependsOn "MyCustomTask_Owner"
extension.users.get().each { user ->
tasks.register("MyCustomTask_${user}", MyTask) {
username = user
}
AllMyCustomTasks.dependsOn "MyCustomTask_${user}"
}
The consumer of the plugin, app/build.gradle
, looks like:
plugins {
id 'com.android.application'
id 'GreetingPlugin'
}
...
greeting {
users = ["John", "Peter", "Paul"]
owner = "Larry"
}
preBuild.dependsOn AllMyCustomTasks
...
After a gradle sync, I expected to see 4 custom tasks: app:MyCustomTask_Owner
, app:MyCustomTask_John
, app:MyCustomTask_Paul
, app:MyCustomTask_Peter
. And when running the build, I expected to see:
...
> Task :app:MyCustomTask_John
Hello John !
> Task :app:MyCustomTask_Owner
Hello Larry !
> Task :app:MyCustomTask_Paul
Hello Paul !
> Task :app:MyCustomTask_Peter
Hello Peter !
> Task :app:AllMyCustomTasks
> Task :app:preBuild
...
However, only the app:MyCustomTask_Owner
task is created.
It is only after I modify buildSrc/src/main/groovy/GreetingPlugin.gradle
by placing
extension.users.get().each { user ->
tasks.register("MyCustomTask_${user}", MyTask) {
username = user
}
AllMyCustomTasks.dependsOn "MyCustomTask_${user}
inside project.afterEvaluate {}
, that all 4 custom tasks are correctly created and the build time output matches what I expected.
So my question is: why is it necessary to wait until the end of configure phase to register 3 of the 4 custom tasks that involve reading the ListProperty of the extension? Why is it that the MyCustomTask_Owner
task, which only involves a Property of the extension, can be defined outside of project.afterEvaluate {}
?