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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With