Call another task from a task in gradle
Gradlebuild.gradleGradle Problem Overview
I'm using Gradle. I have two tasks: "a" and "b". I want task "a" to call task "b". How can I do this?
task b(type: Exec) {
description "Task B"
commandLine 'echo', 'task-b'
}
task a(type: Exec) {
description "Task A"
commandLine 'echo', 'task-a'
// TODO: run task b
}
In Ant this is a piece of cake:
<target name="a">
<echo message="task-a"/>
<antcall target="b"/>
</target>
<target name="b">
<echo message="task-b"/>
</target>
The first method I tried is using the "dependsOn" feature. However this is not ideal as we would need to think of all the tasks in reverse and also has several other issues (like running a task when a condition is satisfied).
Another method I tried is:
b.mustRunAfter(a)
However this only works if I run the gradle tasks like so:
gradle -q a b
Which is also not ideal.
Is there anyway to simply just call another task from an existing task?
Gradle Solutions
Solution 1 - Gradle
As suggested one method would be to add a finalizer for the task
task beta << {
println 'Hello from beta'
}
task alpha << {
println "Hello from alpha"
}
// some condition
if (project.hasProperty("doBeta")) {
alpha.finalizedBy beta
}
Then we can execute the other task if needed. As for executing tasks from another tasks you cannot do that. Task declaration is declarative not imperative. So a task can depend on another task but they cannot execute another task.
$ gradle -q alpha
Hello from alpha
$ gradle -q alpha -PdoBeta
Hello from alpha
Hello from beta
Solution 2 - Gradle
You can use
a.dependsOn 'b'
Or
a.dependsOn b
Or
task a(type: Exec, dependsOn: 'b') { ... }
etc
Solution 3 - Gradle
To summarize and combine the answers from @JBirdVegas and @lance-java, using non-deprecated doLast
instead of leftShift (<<
):
task beta {
doLast {
println 'Hello from beta'
}
}
task alpha {
doLast {
println 'Hello from alpha'
}
}
// some condition
if (project.hasProperty('doBeta')) {
alpha.finalizedBy beta // run 'beta' after 'alpha'
// or
// alpha.dependsOn beta // run 'beta' before 'alpha'
}
Solution 4 - Gradle
It is working fine but providing a warning as Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
I am using gradle version 4.7. So it means some of the features you have added in the build.gradle will not work as it is in gradle 5.0.
Run the Gradle build with a command line argument --warning-mode=all to see what exactly the deprecated features are.
It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.