rmarinsky
rmarinsky

Reputation: 23

How to execute a task in gradle only after build failed

I have folowing code in biuld.gradle:

task generateReport(type: Exec){
    onlyIf{
        project.getState().failure
    }
    doLast{
        executable "generateReport.bat"
    }
}

tasks.withType(Test)*.finalizedBy generateReport

I've tried before:

task generateReport(type: Exec){
    executable "generateReport.bat"
}

tasks.withType(Test)*.finalizedBy generateReport

gradle.afterProject {project, projectState ->
    if (projectState.failure) {
        doLast{
            generateReport
        }
    }
}

And others examples, but all was useless..

What I've done incorrectly?

Upvotes: 2

Views: 2470

Answers (3)

Stanislav
Stanislav

Reputation: 28106

First of all, you have to use a BuildListener as it was mentioned in other answers already. But one more note, you can't call some task the way you did it, with generateReport. So you have rather to use an exec right in the closure of the listener, as:

gradle.buildFinished { buildResult ->
    if (buildResult.failure) {
        exec {
            executable "generateReport.bat"
        }
    }
}

Upvotes: 4

Vampire
Vampire

Reputation: 38669

Project.state is the evaluation state of the project, not some execution state. If you want to do something when the build failed, you should do gradle.addBuildListener() and in the BuildListener implement the method buildFinished() where you can check result.failure to see whether the build failed. If you want to perform some action for each failed test tast, you should instead use gradle.addListener() and give it an implementation of TestListener where you can act on failed tests or test suites. Alternatively you can also add a test listener only to specific test tasks with testTask.addTestListener(). Or to have it even nicer, you can do testTask.afterTest { ... } or testTask.afterSuite { ... }.

Upvotes: 0

tddmonkey
tddmonkey

Reputation: 21184

You need to hook into the buildFinished lifecycle event, like this:

gradle.buildFinished { buildResult ->
    if (buildResult.failure) {
        println "Build Failed!"
    } else {
        println "Build Succeeded!"
    }
}

Upvotes: 4

Related Questions