18

I am trying to run the code block below, after reading multiple posts on the topic and the Gradle manual. I run the below and get the following error: execCommand == null!

Any ideas on what I am doing wrong with the below code block?

open class BuildDataClassFromAvro : org.gradle.api.tasks.Exec() {

    @TaskAction
    fun build() {
        println("Building data classes.....")
        commandLine("date")
    }
}

tasks.register<BuildDataClassFromAvro>("buildFromAvro") {
    description = "Do stuff"
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Dan Largo
  • 1,075
  • 3
  • 11
  • 25
  • 1
    What is it you're trying to get the task to do? An `Exec` task is for running a cmd-line process, so you don't need to actually create a Kotlin class that subclasses it: instead you create a Gradle task of type `Exec` and define the `commandLine` in there (see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html). Are you trying to run a cmd-line process? Or are you trying to write a task that will run some custom Kotlin code? – Yoni Gibbs Feb 04 '20 at 16:50
  • I am trying to run a command line process as part of the build process. – Dan Largo Feb 04 '20 at 17:07

3 Answers3

28

To define a Gradle task that runs a command-line using the Gradle Kotlin DSL do something like this in your build file:

task<Exec>("buildFromAvro") {
    commandLine("echo", "test")
}

In the example above the commandLine will simply run echo, outputting the value test. So replace that with whatever you want to actually do.

You can then run that with gradle buildFromAvro

More info here: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html

Yoni Gibbs
  • 6,518
  • 2
  • 24
  • 37
2

If adding to an existing task:

exec {
    commandLine("echo", "hi")
}

mowwwalker
  • 16,634
  • 25
  • 104
  • 157
0

Another approach is to use the Java ProcessBuilder API:

tasks.create("MyTask") {
    val command = "echo Hello"
    doLast {
        val process = ProcessBuilder()
            .command(command.split(" "))
            .directory(rootProject.projectDir)
            .redirectOutput(Redirect.INHERIT)
            .redirectError(Redirect.INHERIT)
            .start()
            .waitFor(60, TimeUnit.SECONDS)
        val result = process.inputStream.bufferedReader().readText()
        println(result) // Prints Hello
    }
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133