Derrops
Derrops

Reputation: 8107

Configure a Gradle Task at Runtime

Is It possible to configure inputs of a gradle task at runtime after other tasks have run?

For example I am calculating a SHA of a zip in one step, and then uploading the zip with a path consisting of the SHA from a previous step. But when I got get get the value of the SHA which is contained in a file via: def sha = shaFile.text I get an error: (No such file or directory).

I had always assumed tasks were closures which were run at runtime but I guess that is just the doFirst & doLast, but the inputs need to be configured already before that.

Upvotes: 0

Views: 1383

Answers (1)

Cisco
Cisco

Reputation: 22952

Is It possible to configure inputs of a gradle task at runtime after other tasks have run?

Think of it this way:

In order for task B to run, task A must run first, that is to say, task B has a dependency on task A.

Refer to Adding dependencies to a task for more details on task dependencies.

Ok so now we're at the point where we need the output of task A (SHA value) as an input for task B. Since we have a dependency on task A, Gradle well make sure that task A is executed prior to B's execution.

Here's quick dirty example in Kotlin DSL (should be easily translated to Groovy):

tasks {
    val taskA = register("taskA") {
        val shaText = File("sha.txt")
        if (shaText.exists()) {
            shaText.delete()
        }
        File("sha.txt").writeText("abc");
    }
    register("taskB") {
        dependsOn(taskA)
        println(File("sha.txt").readText())
    }
}

Ideally, you should create a custom task type specifying the input file and also specifying the output file so that Gradle can cache tasks inputs/outputs. Refer to Incremental tasks for more details.

Upvotes: 2

Related Questions