kgui
kgui

Reputation: 4163

Testing if gradle task executed

I am working with the axion gradle plugin and my goal is to test if the createRelease task has been executed. If so, I would like to edit a variable that my project depends on. How can I test if a gradle task has been successfully executed. I tried the onlyIf predicate and testing if it is not null but, the latter only tests if the task exists rather than if it was run.

I would like to run this test in the ext closure.

Upvotes: 2

Views: 4128

Answers (2)

Vampire
Vampire

Reputation: 38734

You need to register a listener that is notified on task events, e.g. with gradle.taskGraph.afterTask { if (it == createRelease) { /* do stuff */ } }. But you should not change Gradle configuration in that listener. You should only change configuration in configuration phase. That listener of course is run during execution phase.

You should change your strategy in that case, e.g. by doing gradle.taskGraph.whenReady { if (it.hasTask(createRelease)) { /* do stuff */ } }. The whenReady is done during configuration phase, so you can still configure tasks and so on. So with that line you do stuff if the createRelease task will be run as part of the current Gradle execution.

Upvotes: 3

Lukas Körfer
Lukas Körfer

Reputation: 14543

Every Gradle task provides a TaskState that provides the information you require:

task a { }

task b {
    onlyIf { a.state.executed }
}

You may also use a.state.didWork (or a.didWork), if you want to check whether the task really did something (e.g. a Copy task).

Edit: I just noticed, that you mentioned to use this functionality in a plugin. One example for this use case:

project.gradle.buildFinished {
    if (project.tasks['myTask'].state.executed) {
        // do something
    }
}

Upvotes: 6

Related Questions