Darren Oakey
Darren Oakey

Reputation: 3662

Gradle task doLast if task fails

I want a clean build, where you can see exactly what happened, but all information is preserved - so essentially for every task, I want it to write the output to a file, and only display it if the task fails.

I've tried to achieve this in gradle - but am being defeated because doLast doesn't run if the task fails. Here's my "almost" working pattern:

task fakeTask( type: Exec ) {

    standardOutput = new ByteArrayOutputStream()
    commandLine 'cmd', '/c', 'silly'
    doLast {
        new File("build.log") << standardOutput.toString()
        if (execResult.exitValue != 0) println standardOutput.toString()
    }
}

is there any alternative to doLast that will run any time? Any other way of doing this? - especially as I want to do this for every single task I have?

Upvotes: 7

Views: 6158

Answers (3)

Ivy Gorven
Ivy Gorven

Reputation: 155

You can use the task graph as documented at https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:task_execution to execute code after a task has run.

gradle.taskGraph.afterTask { task, state ->
    if (task instanceof ExecTask && state.failure) {
        file('gradle.log') << standardOutput.toString()
    }
}

Upvotes: 1

Darren Oakey
Darren Oakey

Reputation: 3662

this is my final solution:

tasks.withType( Exec ) {
    standardOutput = new ByteArrayOutputStream()
    ignoreExitValue = true
    doLast {
        new File("gradle.log") << standardOutput.toString()
        if (execResult.exitValue != 0) 
        {
            println standardOutput.toString()
            throw new GradleException(commandLine.join(" ") + " returned exitcode of " + execResult.exitValue )
        }
    }
}

Upvotes: 7

RaGe
RaGe

Reputation: 23805

Add a ignoreExitValue true to your task definition to suppress throwing of an exception when the exit value is non-zero.

Upvotes: 5

Related Questions