Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line argument to Gradle Kotlin DSL

Here's an example from Groovy that represents exactly what I would like to achieve:

Command line:

./gradlew jib -PmyArg=hello

build.gradle.kts

task myTask {
    doFirst {
       println myArg
       ... do what you want
    }
}

Source of this example is here - option 3.

How can I read pass and read myArg value in Kotlin DSL ?

like image 757
skryvets Avatar asked Jun 11 '19 02:06

skryvets


People also ask

How do you pass command line arguments in build Gradle?

When we want to pass input arguments from the Gradle CLI, we have two choices: setting system properties with the -D flag. setting project properties with the -P flag.

How do you pass variables to create Gradle?

If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true" .

How do I run a Gradle program from the command line?

To run a Gradle command, open a command window on the project folder and enter the Gradle command. Gradle commands look like this: On Windows: gradlew <task1> <task2> … ​ e.g. gradlew clean allTests.

What is DSL in Gradle?

Simply, it stands for 'Domain Specific Language'. IMO, in gradle context, DSL gives you a gradle specific way to form your build scripts. More precisely, it's a plugin-based build system that defines a way of setting up your build script using (mainly) building blocks defined in various plugins.


1 Answers

After some time found an answer:

build.gradle.kts

val myArg: String by project // Command line argument is always a part of project

task("myTask") {
    doFirst {
        if (project.hasProperty("myArg")) {
            println(myArg)
        }
    }
}

Command line:

gradle myTask -PmyArg=foo

Output:

$ gradle myTask -PmyArg=foo

> Task :myTask
foo

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

Related links:

  • How to pass arguments from command line to gradle
  • How to pass parameters or arguments into a gradle task
  • Gradle task check if property is defined
like image 50
skryvets Avatar answered Oct 25 '22 17:10

skryvets