Here's a solution that works with any type of Gradle Task
, not only Exec
.
Note: all the examples I provided are in build.gradle.kts format with Gradle lazy configuration syntax.
In your specific case you want either to use a memory cache:
tasks.register<Exec>("sampleTaskWithOutputToFile") {
commandLine ("someCommand", "param1")
val taskOutput = StringBuilder()
logging.addStandardOutputListener { taskOutput.append(it) }
doLast {
project.file("foo.output.txt").writeText(taskOutput.toString())
}
}
or directly write to the file:
tasks.register<Exec>("sampleTaskWithOutputToFile") {
commandLine ("someCommand", "param1")
lateinit var taskOutput: java.io.Writer
doFirst {
taskOutput = project.file("someFolder/someFile.out").writer()
}
logging.addStandardOutputListener { taskOutput.append(it) }
doLast {
// WARNING: if the task fails, this won't be executed and the file remains open.
// The memory cache version doesn't have this problem.
taskOutput.close()
}
}
As a more general answer we could consider that an external plugin registered a foo
task.
tasks.register("foo") {
doLast {
println("warning: some message")
}
}
In the project build script it's possible to capture, and act on the output, even implement "fail-on-warning" pattern.
tasks.named("foo") {
val taskOutput = StringBuilder()
logging.addStandardOutputListener { taskOutput.append(it) }
doLast {
// Usage of taskOutput must be in doLast, after all other task actions have been done.
// Be careful: if there's another `doLast {}` added after this, the output from that won't be considered.
if ("warning:" in taskOutput) {
throw Exception(
"""
There was a problem executing foo, please fix.
""".trimIndent()
)
}
}
}