Custom initialization of custom task

We are writing a custom task. We would like to do some initialization work during the loading phase of the task (Specifically we would like to make this task a dependend of other tasks automatically).

What we do know is this:

class SomeCodeGenerationTask extends DefaultTask {
  @Input
  def schema
    def setSchema(def schema) {
    // We know this code is called in initialization
    this.schema = schema
    initCodeGeneration()
  }
    def initCodeGeneration() {
    // ...
    this.project.tasks.generate.dependsOn this
  }
    @TaskAction
  def generateCode() {
    //...
  }
}

Ideally, we would do something like this:

class SomeCodeGenerationTask extends DefaultTask {
  @Input
  def schema
    @Initialize
  def initCodeGeneration() {
     // ...
    this.project.tasks.generate.dependsOn this
  }
     @TaskAction
  def generateCode() {
      //...
  }
}

Is there a way in gradle to this without “calling the init method in the setter” hack?

A task (type) should get all information it needs injected via configuration properties. It shouldn’t reach out into the project model or make assumptions about other tasks etc. This is what plugins are for.

Yes, that makes sense. Can you give me some guidance on how to make a task automatically depend on another in a custom plugin. There are projects, when there is more then one code generation task. So we cannot automatically assume there is one code generation task, when we apply the plugin.

It depends. For example, the plugin could add a configuration rule such as ‘tasks.withType(SomeTaskType) { dependsOn(…) }’. Or it could allow the user to configure things in terms of higher-level extension object(s) and configure stuff (add tasks, add task dependencies, etc.) based on that information.

This is exactly what we needed. Thanks. And it feels much righter. Plugins for the win!