这是一个适用于任何类型的 Gradle Task 的解决方案,不仅适用于 Exec。
注意:我提供的所有示例都是 build.gradle.kts 格式和 Gradle 惰性配置语法。
在您的特定情况下,您希望使用内存缓存:
tasks.register<Exec>("sampleTaskWithOutputToFile") {
commandLine ("someCommand", "param1")
val taskOutput = StringBuilder()
logging.addStandardOutputListener { taskOutput.append(it) }
doLast {
project.file("foo.output.txt").writeText(taskOutput.toString())
}
}
或直接写入文件:
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()
}
}
作为更一般的答案,我们可以认为外部插件注册了 foo 任务。
tasks.register("foo") {
doLast {
println("warning: some message")
}
}
在项目构建脚本中,可以捕获并处理输出,甚至实现“fail-on-warning”模式。
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()
)
}
}
}