Extension function for capturing Gradle command line tasks

PHOTO EMBED

Wed Jan 26 2022 11:55:22 GMT+0000 (Coordinated Universal Time)

Saved by @larcos #kotlin

/**
 * Captures the output of a Gradle exec command.
 * ####Example:
 * ```
 * tasks {
 *    register<Task>("restartAppServer") {
 *        group = "MyTasks"
 *        description = "Restarts your local PS app server."
 *        val output = execWithOutput {
 *            workingDir(projectDir)
 *            commandLine("cmd", "/c", "restartAppServer.bat")
 *        }
 *        doLast { println(output) }
 *    }
 * }
 * ```
 */
fun Project.execWithOutput(spec: ExecSpec.() -> Unit): String = ByteArrayOutputStream().use { outputStream ->
    exec {
        standardOutput = outputStream
        spec()
    }
    outputStream.toString()
}
content_copyCOPY