Noah Andrews
Noah Andrews

Reputation: 369

How can I make my Gradle plugin auto-execute its tasks?

I’ve written a plugin (which currently just lives in buildSrc) that creates several tasks whose names are based on values provided by the user. How can I make it so that they execute whenever the build script that applies the plugin is run? It doesn't need to run at any specific point in the execution phase.

Upvotes: 3

Views: 2031

Answers (2)

Lukas Körfer
Lukas Körfer

Reputation: 14493

To start off with, you work around a basic Gradle concept. A Gradle task is not designed to run on every Gradle invocation. If you really need code to run on each Gradle invocation, execute it directly during configuration phase instead of wrapping it inside a task.

However, there are two causes for a task to run on a Gradle build:

  • direct selection (via command line or settings.startParameter.taskNames modification)
  • via one or more task dependencies (dependsOn / finalizedBy)

Of course you can use one of these methods to circumvent Gradle and execute your task on each build (@mkobit used the second method), but since your plugin would basically break basic Gradle principles, your solution may fail at some future time or for a more complex project (since plugins are supposed to be reusable).

As a summary, I would recommend to bundle all your generated tasks in one task with a constant name, so that your user can easily run the task on each Gradle invocation by putting a single line in his settings.gradle file:

startParameter.taskNames.add '<bundleTask>'

Upvotes: 2

mkobit
mkobit

Reputation: 47259

One way you could accomplish this is to use the all method on the TaskCollection to add a dependsOn/finalizedBy relationship to all (or some) tasks in the project.

Example to create a single myTask with every task in allproject depending on it:

class MyPlugin implements Plugin<Project> {
  void apply(final Project project) {
    final myTask = project.tasks.create('myTask')
    project.allprojects.each { proj ->
      proj.tasks.all {
        // Make sure to not add a circular dependency
        if (it != myTask) {
          it.dependsOn(myTask)
        }
      }
    }
  }
}

Upvotes: 1

Related Questions