Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call another task from a task in gradle

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?

like image 441
Yahya Uddin Avatar asked Nov 15 '16 14:11

Yahya Uddin


People also ask

Can task call another task?

Task declaration is declarative not imperative. So a task can depend on another task but they cannot execute another task.

How do I run multiple tasks in Gradle?

Executing Multiple Tasks You can execute multiple tasks from a single build file. Gradle can handle the build file using gradle command. This command will compile each task in such an order that they are listed and execute each task along with the dependencies using different options.

What is doLast in Gradle?

The doLast creates a task action that runs when the task executes. Without it, you're running the code at configuration time on every build. Both of these print the line, but the first one only prints the line when the testTask is supposed to be executed.


1 Answers

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 
like image 117
JBirdVegas Avatar answered Sep 20 '22 10:09

JBirdVegas