Understanding Gradle task dependency (dependsOn)
Two questions:
- What is the gradle way to specify that 1 task is comprised of several other tasks?
- It seems like gradle's
taskName.execute()
method does not honor the dependsOn relationships oftaskName
is this true and what is the work-around?
More background:
Right now I have a build script that has no plugins (not Java in other words). I want a task called tests
that will run all my test tasks. I have 3 such tasks. Call them task1, task2, and task3.
I could say tests.dependsOn ['task1', 'task2', 'task3']
This is a bit wonky because the relationship seems to be tests.isComprisedOf ['task1', 'task2', 'task3']
I could say:
task tests << {
task1.execute()
task2.execute()
task3.execute()
}
but then task3, which itself depends on taskSetup, runs without running taskSetup. In other words the execute() call does not seem to honor gradle's dependencies resolution strategy.
One last small gripe (I really do love gradle by the way), is that it is hard to search on this topic because dependency means two different things in gradle: dependsOn style dependencies and library style dependencies.
Solution 1:
Typically, you do not invoke task.execute()
.
You can specify that one task is comprised of other tasks in the following manner:
task task1 << {
println "Hello"
}
task task2 << {
println "World"
}
task task3(dependsOn: 'task3dependency') << {
println "QBert"
}
task task3dependency << {
println "MR"
}
task tests(dependsOn: ['task1', 'task2', 'task3'])
This outputs:
$ gradle tests
:task1
Hello
:task2
World
:task3dependency
MR
:task3
QBert
:tests
BUILD SUCCESSFUL
Keep in mind that the order in which your dependency tasks are run is not always guaranteed, but you can mitigate this by specifying the order task2.mustRunAfter task1
. Usually though, the tasks are run in the order you would expect.
Also, you should read up on Gradle's Build Lifecycle. When you use the syntax task task1 << {...}
, you are specifying a closure that is run in the execution phase of the task. Before execution is run, the configuration phase evaluates your build script and determines the tasks to be run and in what order. When you manually execute tasks, as in:
task tests << {
task1.execute()
task2.execute()
task3.execute()
}
you have bypassed Gradle's ability to evaluate the task dependencies of task3, hence it runs only task3.
Solution 2:
Gradle's task model is "flat" and doesn't have a concept of aggregation. (It's important to note that TaskInternal#execute
is an internal method, and must not be called from build scripts.) Aggregation is often simulated with a lifecycle task (a task with task dependencies but without any task actions):
task allTests {
dependsOn tasks.withType(Test)
}
Besides dependsOn
, the following task relationships are supported: mustRunAfter
, shouldRunAfter
, and finalizedBy
.