12

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 ?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
skryvets
  • 2,808
  • 29
  • 31

2 Answers2

16

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:

skryvets
  • 2,808
  • 29
  • 31
  • 1
    That doesn't work (for me), since variable `myArg` is undefined at compile time of build.gradle.kts. It works with `project.properties["myArg"]`. – deamon Mar 08 '23 at 12:13
3

I retrieved the argument for my task like this (build.gradle.kts with Kotlin DSL):

tasks.create("myCustomTask") {
  doLast {
    val myArg = properties["myArgName"]
    // OR a more verbose form:
    val myArg = project.properties["myArgName"]
  }
}
./gradlew myCustomTask -PmyArgName=hello
Mahozad
  • 18,032
  • 13
  • 118
  • 133