Anatomy of a Gradle Task: Task Dependencies
root
Here’s another little “gotcha” on gradle tasks. When they’re triggered. I’ve seen quite a few posts on stackoverflow along the lines of “How can I call a gradle task”. You can’t (Well ok you could but you don’t want to). It is executed as a dependency of another task.
Going back to that little copy task I wanted to execute, I needed it to run roughly somewhere after the clean task and before jar task. I ended up making my copy task dependent of compile. That didn’t work so I tried compileJava and classes and… only to later realize that the dependency was in the wrong direction: My task depends on one that is being executed but that doesn’t trigger my task, it merely states that my task, should it be executed, can only be run after some other task.
So let’s revert the direction of the dependency. There are several ways to do this and I don’t know if there’s a best practice. Here are a few variations:
// define standalone task
task messageBundlesCopy(type: Copy) {
from "src/main/java"
include "**/*.properties"
into sourceSets.main.output.resourcesDir
}
// manipulate dependencies
jar.dependsOn += messageBundlesCopy
// slight variation of the above, eliminates the need to use the task name explicitly multiple times
task messageBundlesCopy(type: Copy) {
from "src/main/java"
include "**/*.properties"
into sourceSets.main.output.resourcesDir
jar.dependsOn += name // assign this task's name as dependency for the jar task
}
// append the copy task to compileJava (or any other task that is executed before jar)
// instead of "<<" one could also use ".doLast"
compileJava << {
copy {
from "src/main/java"
include "**/*.properties"
into sourceSets.main.output.resourcesDir
}
}
// prepend the copy task to the jar task, there's no special operator for doFirst, only for doLast so no shortcut there
jar.doFirst {
copy {
from "src/main/java"
include "**/*.properties"
into sourceSets.main.output.resourcesDir
}
}
I currently use the first variation because my task is standalone and I only need to define the task dependencies. However, the jar.doFirst approach has its appeal too since it’s nice and short. I’m just reluctant to manipulate the logic of an existing task provided by a plugin.
What I haven’t figured out yet, is how to put the task into a variable and have the ability to reuse it for several modules of my projects.