Gradle lazy Exec-Task configuration

Viewed 297

I'm running into a problem when configuring an Exec-Task using an Extension-Property.

Problem

The configuration of my Exec-Task relies on a String-Property that is defined in an extension. Unfortunately, the property is not set yet, when configuring the Exec-Task. This leads to an TaskCreationException:

Could not create task ':myTask'.
org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':myTask'.
    ...
Caused by: org.gradle.api.internal.provider.MissingValueException: Cannot query the value of extension 'myConfig' property 'command' because it has no value available.
    at org.gradle.api.internal.provider.AbstractMinimalProvider.get(AbstractMinimalProvider.java:86)

Example

abstract class ConfigExtension() {
    abstract val command: Property<String>
}

class MyGradlePlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val myConfig = project.extensions.create(
            "myConfig",
            ConfigExtension::class.java
        )

        val myTask = project.tasks.register(
            "myTask",
            Exec::class.java
        ) {
            it.commandLine(myConfig.command.get())
        }
    }
}

The problem seems to be the myConfig.command.get() which circumvents the lazy evaluation.

Test

@Test fun `plugin registers task`() {
    // Create a test project and apply the plugin
    val project = ProjectBuilder.builder().build()
    project.plugins.apply("com.example.plugin")

    // Verify the result
    assertNotNull(project.tasks.findByName("myTask"))
}

Question

Is there a way to configure the commandLine-Value in a lazy manner like gradle tasks should be configured? [1] [2]

0 Answers
Related