Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use parameters in gradle tasks?

Tags:

gradle

There are many tasks that come with gradle which use parameters.

gradle test --tests *Test
gradle dependencyInsight --dependency junit

How can I access parameters in my own custom tasks?

like image 390
John Mercier Avatar asked Aug 30 '16 15:08

John Mercier


People also ask

How do you pass arguments in Gradle task?

Here, we don't use properties to pass arguments. Instead, we pass the –args flag and the corresponding inputs there. This is a nice wrapper provided by the application plugin. However, this is only available from Gradle 4.9 onward.

How do I pass environment variables in Gradle task?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables.

How do I pass properties to Gradle?

Using the -D command-line option, you can pass a system property to the JVM which runs Gradle. The -D option of the gradle command has the same effect as the -D option of the java command. You can also set system properties in gradle. properties files with the prefix systemProp.


1 Answers

I recently stumbled upon @Option in some internal Gradle task (JavaExec, I think). The JavaDoc of the annotation reads exactly like what you are looking for, but it was 'internal' API. The functionality is part of the public API starting with Gradle 4.6: See release notes and user guide.

Just tested this:

import org.gradle.api.tasks.options.Option

class MyTask extends DefaultTask {
    @Option(option="funky", description="test")
    String myOption

    @TaskAction
    void echoOption() {
        logger.lifecycle("Value of 'myOption': ${myOption}")
    }
}

task myTask(type: MyTask) {
}

Result:

$ gradle myTask --funky=foo
:myTask
Value of 'myOption': foo

BUILD SUCCESSFUL

Total time: 0.845 secs
like image 94
Axel von Engel Avatar answered Sep 20 '22 07:09

Axel von Engel