Gradle task rules

Gradle allows you do define task rules which will be invoked when unknown task is requested. Task rules can become handy when you have to define a behaviour which depends on infinite number of inputs. For example, you want to create a task which will run all unit tests in a specific directory, this can be done using gradle task rules.

  • Example
tasks.addRule("RunTest: directory") {
    val taskName = this // the task name
    if (startsWith("runTest")) {
        task(taskName) {
            doLast {
                println("running tests in dir " + (taskName.replace("runTest", "")))
            }
        }
    }
}
  • gradle -q runTestRoot
//ouput
running tests in dir Root

tasks.addRule(description) will add a task rule which will be invoked when an unknown task is requested by gradle.

In our example, when runTestRoot task was requested, gradle checked if it is defined or not, because the task was not defined, therule was executed with the task name (runTestRoot) where we checked if name starts with runTest then create a task with that name and a given action doLast.

After the rule execution created the given task, gradle can now fund/run it. If no task with the given name was created, gradle will throw task not found exception.

Note that other tasks can also depend on task rules. For our given example, we can create another task which will run test in different directories. See example below

tasks.register("runAllCoreTests") {
    // depends on task rule
    dependsOn("runTestRoot", "runTestOther")
    doLast {
        println("task ${this.name} completed")
    }
}
  • gradle -q runAllCoreTests
// output

running tests in dir Other
running tests in dir Root
task runAllCoreTests completed

top