Fontanka16
Fontanka16

Reputation: 1321

Make Gradle build halt/fail on failing Exec task based on output

We use an Exec task for running Webpack in our Gradle build definition. This task fails sometimes, but the build task completes and our Jenkins server thinks everything went well and publishes the war file with corrupt client code in it.

In the output from the Exec task you can see that Webpack gets an error and halts.

I now wonder if it is possible to make my Exec task consume the output and react on it before exiting so that i can make the task fail.

i have played with setStandardOutput() and standardOutput, but i cannot seem to get it to work.

Below is my task definition

task webpack(type: Exec) {
    def mainCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'webpack.cmd' : 'webpack'

    if (project.environment == 'prod')
        commandLine mainCommand, '-p'
    else
        commandLine mainCommand
}

Upvotes: 2

Views: 884

Answers (1)

Fontanka16
Fontanka16

Reputation: 1321

This seems to work fine for me. It parses the output and if the output contains a line that begins with "error" the task fails.

task webpack(type: Exec) {
    def mainCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'webpack.cmd' : 'webpack'
        standardOutput = new ByteArrayOutputStream()
        if (project.environment == 'prod')
            commandLine mainCommand, '-p'
        else
            commandLine mainCommand

    doLast {
        String output = standardOutput.toString()

        if(output.readLines().any{line->line.trim().toLowerCase().startsWith("error")}) {
            throw new GradleException("Error in WebPack: \n${output}")
        } else {
            println "Great success! Output is: ${output}"
        }
    }

}

Upvotes: 1

Related Questions