Call another task from task in gradle

I am 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" function. However, this is not ideal, since we will need to think about all the tasks in the reverse order and also have several other problems (for example, performing a task when the condition is met).

Another method I tried:

b.mustRunAfter(a)

However, this only works if I run the gradle tasks as follows:

gradle -q a b

This is not perfect either.

Is it possible to simply call another task from an existing task?

+4
source share
3

,

task beta << {
    println 'Hello from beta'
}

task alpha << {
    println "Hello from alpha"
}

// some condition
if (project.hasProperty("doBeta")) {
    alpha.finalizedBy beta
}

, . , . . , , .

$ gradle -q alpha
Hello from alpha
$ gradle -q alpha -PdoBeta
Hello from alpha
Hello from beta
+7

a.dependsOn 'b'

a.dependsOn b

task a(type: Exec, dependsOn: 'b') { ... }

..

.

+6

To summarize and combine the answers from @JBirdVegas and @ lance-java, using not deprecated doLastinstead 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'
}
+5
source

Source: https://habr.com/ru/post/1660807/


All Articles