LaVOZs

The World’s Largest Online Community for Developers

'; In Gradle (6.2), can we annotate constructor params of a custom task as "input"? - LavOzs.Com

Say I have a custom gradle task:

open class CustomTask @Inject constructor(
    private val inputFile: File,
    private val outputFile: File
    ) : DefaultTask()

(based on https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:passing_arguments_to_a_task_constructor ) .

In gradle, so far, the common way to define inputs or outputs is with annotations like InputFile.

From a Kotlin-perspective, it would be nice to inject all these input/output values in the constructor, but I'm wondering, is it possible? Something like:

open class CustomTask @Inject constructor(
private @InputFile val inputFile: File,
private @OutputFile val outputFile: File

) : DefaultTask()

The javadocs for both annotations state (emphasis mine):

@InputFile

This annotation should be attached to the getter method in Java or the property in Groovy. Annotations on setters or just the field in Java are ignored.

@OutputFile

This annotation should be attached to the getter method in Java or the property in Groovy. Annotations on setters or just the field in Java are ignored.

To answer your question: no.

Constructor arguments in Kotlin, Java, or Groovy are neither getters nor properties so they are ignored.

Actually, it works like I asked above!

I didn't expect that it would, based on the docs, which is why I originally asked the question.

But the following task, defined like this in Kotlin (under /buildSrc) works:

open class TaskA @Inject constructor(
        @org.gradle.api.tasks.InputFile var inputFile : File,
        @org.gradle.api.tasks.OutputFile var outputFile : File
) : DefaultTask() {

    @TaskAction
    fun doIt() {
        val contents = inputFile.readText()
        val result = contents.replace("a", "b")
        outputFile.parentFile.mkdirs()
        outputFile.writeText(result)
    }
}
Related
How can I force gradle to redownload dependencies?
Gradle: Force Custom Task to always run (no cache)
In gradle, how to set a directory (recursively) as the output of a task? (to be checked and hashed for UP TO DATE checking)
Accessing Gradle inputs in task constructor
How can I use third party dependencies in custom task under buildSrc in Gradle
Convert ant signJar task to gradle
How do I specify optional inputs on a Gradle task without an @Optional annotation?
How to convert gradle ant java task to kotlin
Make custom Gradle task, that generates code, run on IDE import
Gradle Kotlin DSL: how to configure subprojects using typesafe api