Home > Software design >  How to pass @Input String in a task in buildSrc
How to pass @Input String in a task in buildSrc

Time:12-14

This custom plugin exists in gradle's buildSrc/:

abstract class MyTask : DefaultTask() {

    @get:Input
    abstract val buildDir: Property<String>

    @TaskAction
    fun someTask() {
       // do stuff
    }
}

class DevelopmentPlugin : Plugin<Project> {

    override fun apply(project: Project) {
        project.tasks.run {
            register("myTask", MyTask::class.java) {

                inputs.property("buildDir", project.buildDir)

                println(inputs.getProperties())
            }
        }
    }
}

and by running the task with e.g. $ ./gradlew myTask fails with:

Could not determine the dependencies of task ':myTask'.
> Cannot query the value of task ':myTask' property 'rootDir' because it has no value available.

Also the prinln outputs {buildDir=null} meaning that the inputs.property("buildDir", project.buildDir) has failed.


How to pass the project.buildDir value from the Plugin in the task?

Using project.buildDir directly from inside the task is not an acceptable answer due to Gradle's incubating build-cache functionality.

CodePudding user response:

Firstly, there is a class type issue which is not visible in Gradle.

buildDir is of type File while the property is String.

So "${project.buildDir}" should be used.

Secondly, since the property is abstract val it can directly be accessed in the closure. Therefore it can be set with:

// instead of:
inputs.property("buildDir", "${project.buildDir}")
// just this:
buildDir.set("${project.buildDir}")
  • Related