HoldYourWaffle
HoldYourWaffle

Reputation: 85

Defining a task dependency inside gradle plugin

I'm trying to fix a gradle plugin that checks for TODO-tags.

This plugin adds a new task (checkTodo) which can be used to run the checks. This task isn't running automatically, but this can be done by adding this line to your build.gradle: check.dependsOn checkTodo

I want to remove the need for this line in every build.gradle that uses this plugin by declaring this dependency in the plugin itself. Is this possible?

Things I've tried:

static void applyTasks(final Project project) {
    TodoTask task = project.tasks.create("checkTodo", TodoTask)

    project.task('check').dependsOn(task)
    project.tasks().task('check').dependsOn(task)
    project.tasks().check
    project.getAllTasks(true).get('check').dependsOn(task)
    project.getDefaultTasks().get('check').dependsOn(task)
}

project.task('check').dependsOn(task) gives:

Failed to apply plugin [class 'org.gradle.language.base.plugins.LifecycleBasePlugin']

Declaring custom 'check' task when using the standard Gradle lifecycle plugins is not allowed.`

The set of project.getAllTasks(true).get(project) doesn't contain the "check" task, and the others just give "no method found" errors.

Upvotes: 3

Views: 1853

Answers (1)

Lukas Körfer
Lukas Körfer

Reputation: 14543

The problem is, that the specific (or any) check task may not exist at the time you apply your plugin.

To ensure the creation of all tasks (even via user code in build.gradle), use the afterEvaluate closure. Please note that this method will still fail, if no task called check will be created in the entire build.

project.afterEvaluate {
    project.tasks['check'].dependsOn task
}

If you want to depend on the task creation of a specific plugin (e.g. the Java plugin), use withId or withPlugin method of the project plugin manager. The given closure will be executed if and when the specific plugin is applied.

project.pluginManager.withPlugin('java') {
    project.tasks['check'].dependsOn task
}

Upvotes: 2

Related Questions