Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use exec() output in gradle

Tags:

gradle

People also ask

What is doLast in Gradle?

The doLast creates a task action that runs when the task executes. Without it, you're running the code at configuration time on every build. Both of these print the line, but the first one only prints the line when the testTask is supposed to be executed.

How do I run Gradle task in debug mode?

Just run gradle run --debug-jvm . This starts the application in remote debug mode, and you can attach with any remote debugger, e.g., Eclipse, on port 5005 . Assuming you use Eclipse as IDE: In Eclipse, go on your Project -> Debug as... -> Debug Configuration -> Remote Java Application.

What is Gradle execution?

In Gradle terms this means that you can define tasks and dependencies between tasks. Gradle guarantees that these tasks are executed in the order of their dependencies, and that each task is executed only once. These tasks form a Directed Acyclic Graph.


This is my preferred syntax for getting the stdout from exec:

def stdout = new ByteArrayOutputStream()
exec{
    commandLine "whoami"
    standardOutput = stdout;
}
println "Output:\n$stdout";

Found here: http://gradle.1045684.n5.nabble.com/external-process-execution-td1431883.html (Note that page has a typo though and mentions ByteArrayInputStream instead of ByteArrayOutputStream)


This post describes how to parse the output from an Exec invocation. Below you'll find two tasks that run your commands.

task setWhoamiProperty {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'whoami'
                standardOutput = os
            }
            ext.whoami = os.toString()
        }
    }
}

task setHostnameProperty {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'hostname'
                standardOutput = os
            }
            ext.hostname = os.toString()
        }
    }
}

task printBuildInfo {
    dependsOn setWhoamiProperty, setHostnameProperty
    doLast {
         println whoami
         println hostname
    }
}

There's actually an easier way to get this information without having to invoke a shell command.

Currently logged in user: System.getProperty('user.name')

Hostname: InetAddress.getLocalHost().getHostName()


Using the kotlin-dsl:

import java.io.ByteArrayOutputStream

val outputText: String = ByteArrayOutputStream().use { outputStream ->
  project.exec {
    commandLine("whoami")
    standardOutput = outputStream
  }
  outputStream.toString()
}

Groovy allows for a much simpler implementation in many cases. So if you are using Groovy-based build scripts you can simply do this:

def cmdOutput = "command line".execute().text