eleven
eleven

Reputation: 6857

Passing parameters to dependable task of custom task

There is task which can be executed with parameter like this:

./gradlew taskX -Pkey=value

And plugin with custom task which should execute taskX:

class CustomPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        project.tasks.register("custom", CustomTask::class.java)
            .configure {
                it.description = "Description"
                it.group = "Group"

                val taskX = project.getTasksByName("taskX", true).first()

                it.dependsOn(taskX)
            }
    }
}

I would expect something like this for example:

it.dependsOn(taskX, "key=value")

How to pass parameters to dependsOn?

Upvotes: 0

Views: 3008

Answers (1)

Lukas K&#246;rfer
Lukas K&#246;rfer

Reputation: 14503

Simple answer: You can't. Task dependencies only express what needs to be done beforehand, not how it needs to be done.


Let me show you a simple example, why something like this is not possible in the Gradle task system:

First, we need to know that in Gradle, every task will be executed only once in a single invocation (often called build). Now imagine a task that needs to be run before two tasks that are unrelated to each other. A good real world example is the task compileJava from the Java plugin that both the test task and the jar task depend on. If dependsOn would support parameters, it could happen that two tasks depend on a single task with different parameters. What parameters should be used in this case?

As a solution, you may configure the other task directly in your plugin. If you want to pass the parameter only if your custom task is run, you may need to add another task that runs as a setup and applies the required configuration to the actual task:

task setup {
    doFirst {
        // apply configuration
    }
}

taskX.mustRunAfter setup

task custom {
    dependsOn setup
    dependsOn taskX
}

This example uses Groovy, but it should be possible to translate it to Kotlin and use it in your plugin.


Edit regarding actual parameter

To be honest, I am not that familiar with the Android Gradle plugin, but if I get this documentation right, the project property android.testInstrumentationRunnerArguments.annotation is just an alternative to using the following code in the build script:

android {
    defaultConfig {
        testInstrumentationRunnerArgument 'annotation', '<some-value>'
    }
}

You may try to define the following task and then run it using ./gradlew customTest

task customTest {
    doFirst {
        android.defaultConfig.testInstrumentationRunnerArgument 'annotation', '<some-value>'
    }
    finalizedBy 'connectedAndroidTest'
}

Upvotes: 1

Related Questions