Creating a task that runs before all other tasks in gradle

Ori Wiesel picture Ori Wiesel · Jul 19, 2017 · Viewed 8.9k times · Source

I need to create an initialize task that will run before all other task when I execute it.

task A {
    println "Task A"
}

task initializer {
   println "initialized"
}

If I execute gradle -q A, the output will be:

>initialized

>Task A

Now if i'll add:

task B {
    println "Task B"
}

Execute gradle -q B, and I get:

>initialized

>Task B

So it doesn't matter which task I execute, it always get "initialized" first.

Answer

lance-java picture lance-java · Jul 19, 2017

You can make every Task who's name is NOT 'initializer' depend on the 'initializer' task. Eg:

task initializer {
   doLast { println "initializer" }
}

task task1() {
   doLast { println "task1" }
}

// make every other task depend on 'initializer'
// matching() and all() are "live" so any tasks declared after this line will also depend on 'initializer'
tasks.matching { it.name != 'initializer' }.all { Task task ->
    task.dependsOn initializer
}

task task2() {
   doLast { println "task2" }
}

Or you could add a BuildListener (or use one of the convenience methods eg: Gradle.buildStarted(...))