Gradle – Call another task from a task in gradle

build.gradlegradle

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?

Best Answer

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