How to execute a task in gradle only after build failed - gradle

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?

You need to hook into the buildFinished lifecycle event, like this:
gradle.buildFinished { buildResult ->
if (buildResult.failure) {
println "Build Failed!"
} else {
println "Build Succeeded!"
}
}

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"
}
}
}

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 { ... }.

Related

How to run certain task with gradle

I try to investigate a Gradle and follows some tutorials, but I have confused with the following:
I created are a couple of simple tasks:
task startProcess{
println 'startProcess'
}
task doStep2{
println 'Step2'
}
task doStep3{
println 'Step3'
}
task finishProcess{
println 'finishProcesss'
}
And try to execute one of them:
gradle finishProcess
Or with defaultTasks with command gradle build:
defaultTasks `finishProcess`
task startProcess{
println 'startProcess'
}
task doStep2{
println 'Step2'
}
task doStep3{
println 'Step3'
}
task finishProcess{
println 'finishProcesss'
}
In both options, I got the same result:
> Configure project :
startProcess
Step2
Step3
finishProcesss
BUILD SUCCESSFUL in 1s
How to execute exactly one of them?
You have to use register, I think if you did not use it, You're only asking Gradle to execute these tasks.
for example
tasks.register('startProcess') {
doLast {
println 'startProcess'
}
}
tasks.register('doStep2') {
doLast {
println 'Step2'
}
}
tasks.register('doStep3') {
doLast {
println 'Step3'
}
}
tasks.register('finishProcess') {
doLast {
println 'finishProcesss'
}
}
tasks.named("build") { finalizedBy("finishProcess") }
Registering these tasks, you will be able to call each one indivadually.
If you want to link a specific task, with a build task for example.
Then you can use finalizedBy like the following.
tasks.named("build") { finalizedBy("finishProcess") }
This will call the finishProcess task, whenever build is triggered.
I strongly recommend the official gradle documintation for more information about tasks.

Execute gradle task after test

After executing test task in Gradle build I want to always execute additional task which should have access to test result. Something like:
task('afterTest') {
doLast {
if (testSuccessful) {
//
} else {
//
}
}
}
There are two parts in your question: 1) make a custom task executed always after test task is executed, 2) make the test "result" available in this custom task.
1) First part is very simple, you just have to use the dedicated Task.finalizedBy method to create a "finalized by" dependency between test task and your custom task. (see Finalizer tasks)
2) Second part is a bit tricky, as there is no simple way provided by Gradle, as far as I know, to get the "result" (SUCCESS or FAILURE) of test task. But you could use API exposed by the Test Task to store the number of test in error into a variable and test this counter in your custom task : here is a working example:
ext{
// counter of test cases in error
nbTestOnError = 0
}
test {
// use "afterTest" hook to increment nbTestOnError counter
afterTest { desc , result ->
if (result.getResultType().equals(TestResult.ResultType.FAILURE)){
nbTestOnError++
}
}
}
task('afterTest') {
doLast {
// implement your logic depending on counter value
if (nbTestOnError > 0) {
// do something if test failed
} else{
// do something when all tests passed
}
}
}
// create "finalized by" dependency
test.finalizedBy afterTest
EDIT : based on important remark in comment from #lance-java : in order to support up-to-date check , you could configure your custom task to be "skipped" if test task is not executed. A simple way would be to use Task upToDateWhen feature (see here) :
task('afterTest') {
// consider this task "UP TO DATE" if `test` task did not execute
outputs.upToDateWhen {
!test.didWork
}
doLast {
//...
}
}
As I said in the other thread, it's best to use the file system to pass values from one task to another. This way the value will be available even if the test task was up to date and skipped. Eg:
test {
outputs.file "$buildDir/test.properties"
ext.errorCount = 0
afterTest { desc , result ->
if (result.resultType.name() == "FAILURE") {
errorCount++
}
}
doLast {
file("$buildDir/test.properties").text = "errorCount=$errorCount"
}
finalizedBy 'afterTest'
ignoreFailures = true
}
task afterTest {
dependsOn 'test'
inputs.file "$buildDir/test.properties"
doLast {
def props = new Properties()
props.load(file("$buildDir/test.properties"))
def errorCount = Integer.parseInt(props['errorCount'])
if (errorCount) {
// doStuff
throw new TaskExecutionException("$errorCount tests failed")
}
}
}
Building on the existing answers, use org.gradle.api.tasks.testing.Test.afterSuite to save the test result to a file:
test {
afterSuite { descriptor, result ->
if (descriptor.parent == null) {
file("$buildDir/test.result").text = result.resultType
}
}
}
afterTest.onlyIf {
file("$buildDir/test.result").text == 'SUCCESS'
}
where the afterTest task is executed only when the test suite succeeds.

Creating a task that runs before all other tasks in gradle

I need to create an initialize task that will run before all other task when I execute it.
task A {
println "Task A"
}
task initializer {
println "initialized"
}
If I execute gradle -q A, the output will be:
>initialized
>Task A
Now if i'll add:
task B {
println "Task B"
}
Execute gradle -q B, and I get:
>initialized
>Task B
So it doesn't matter which task I execute, it always get "initialized" first.
You can make every Task who's name is NOT 'initializer' depend on the 'initializer' task. Eg:
task initializer {
doLast { println "initializer" }
}
task task1() {
doLast { println "task1" }
}
// make every other task depend on 'initializer'
// matching() and all() are "live" so any tasks declared after this line will also depend on 'initializer'
tasks.matching { it.name != 'initializer' }.all { Task task ->
task.dependsOn initializer
}
task task2() {
doLast { println "task2" }
}
Or you could add a BuildListener (or use one of the convenience methods eg: Gradle.buildStarted(...))
Seems like you aim execution phase, and you want a task precursing each task or just run as a first task in the execution phase?
If you want a task to always execute in every project before each other task after its being evaluated you can add a closure to he main build.gradle:
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.YourTask)
task.dependsOn rootProject.tasks.YourTask
}
}
or
tasks.matching {it != YourTask}.all {it.dependsOn YourTask}
You can also use the Task Execution Graph to define the lifecycle. There are few ways of achieving your goal, depending on your needs and a project structure.
The previously suggested solution with dependsOn works fine, but I don't like about it that it changes and clutters the task dependencies. The first solution coming to my mind is using Gradle Initialization Scripts. They are really cool. But, the usage is a bit tedious: currently there is no way to have a default project-local Gradle init script. You have to either explicitly specify the script(s) on command line, or place them in USER_HOME/GRADLE_HOME.
So another solution (already briefliy mentioned by #lance-java) which can be used to run some initialization, like a init task/script, is "build listeners". Depending on how early/late the initialization code should run, I use one of these two:
gradle.afterProject {
println '=== initialized in afterProject'
}
or
gradle.taskGraph.whenReady {
println '=== initialized in taskGraph.whenReady'
}
Here the docs of the Gradle interface and of BuildListener.
Note that some of the events occur very early, and you probably can't use them because of that, like e.g. beforeProject and buildStarted (explanations here and there).

Gradle: custom message on task failure?

I'd like to hook into the compileJava target and spit out an additional custom message on failure. We've got a really common case setup case that a lot of folks overlook and it'd be useful, only on failure, to be able to do something like:
compileJava.onFailure {
println "Did you configure your wampfrankle to talk to the slackometer?"
}
My Google skills have not yet led to an answer.
The error is a dependency error and as Rene points out that needs to be detected after the build has executed, not after the project has been evaluated.
Here I've added a call to buildFinished with a closure that detects if a failure has happened and prints out an error message.
project.gradle.buildFinished { buildResult ->
if (buildResult.getFailure() != null) {
println "Did you configure your wampfrankle to talk to the slackometer?"
}
}
To test this I force a dependency resolution failure with this bogus dependency:
dependencies {
compile 'foo:bar:baz'
}
Use finalizedBy on a task that executes onlyIf the first task fails. For example:
tasks.compileJava.finalizedBy('compileJavaOnFailure')
task compileJavaOnFailure {
doLast {
println 'Did you configure your wampfrankle to talk to the slackometer?'
}
onlyIf {
tasks.compileJava.state.failure != null
}
}

How to create gradle task which always runs?

I'm likely overlooking something pretty core/obvious, but how can I create a task that will always be executed for every task/target?
I can do something like:
task someTask << {
println "I sometimes run"
}
println "I always run"
But it would be much more desirable to have the always running part in a task.
The closest I've come is:
task someTask << {
println "I sometimes run"
}
println "I always run"
void helloThing() {
println "I always run too. Hello?"
}
helloThing()
So, using a method is an 'ok' solution, but I was hoping there'd be a way to specifically designate/re-use a task.
Hopefully somebody has a way to do this. :)
Assuming the goal is to print system information, you could either just always print the information in the configuration phase (outside a task declaration), and have a dummy task systemStatus that does nothing (because the information is printed anyway). Or you could implement it as a regular task, and make sure the task always gets run by adding ":systemStatus" as the first item of gradle.startParameter.taskNames (a list of strings), which simulates someone always typing gradle :systemStatus .... Or you could leverage a hook such as gradle.projectsLoaded { ... } to print the information there.
This attaches a closure to every task in every project in the given build:
def someClosure = { task ->
println "task executed: $task"
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
task << someClosure
}
}
If you need the function/closure to be called only once per build, before all tasks of all projects, use this:
task('MyTask') << {
println 'Pre-build hook!'
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.MyTask)
task.dependsOn rootProject.tasks.MyTask
}
}
If you need the function/closure to be called only once per build, after all tasks of all projects, use this:
task('MyTask') << {
println 'Post-build hook!'
}
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.MyTask)
task.finalizedBy rootProject.tasks.MyTask
}
}
What's wrong with invoking it straight from the root build.gradle?
task init << {
println "I always run"
}
tasks.init.execute()

Resources