gradlegradle-taskgradle-custom-plugin

Can a standalone gradle plugin export a custom task type?


I have a standalone Gradle plugin that includes a custom task type:

gradle-conventions/build.gradle

plugins {
  id 'groovy-gradle-plugin'
  id 'maven-publish'
}

group = 'com.example'
version = '1.0'

publishing {
  repositories {
    maven {
      url = uri('/path/to/repo')
    }
  }
}

gradle-conventions/src/main/groovy/com.example.my-conventions.gradle

abstract class CustomTask extends DefaultTask {
    @TaskAction
    def hello() {
        println "hello"
    }
}

I can consume the plugin from another project, but how can I register a CustomTask? Something like this:

project/build.gradle

plugins {                                                                       
  id 'com.example.my-conventions' version '1.0'
}

// how do I reference CustomTask here?
tasks.register('myCustomTask', com.example.CustomTask) {
  // ...
}

Is it possible to export a custom task from a custom plugin? Or must I consume custom tasks using the buildscript mechanism?


Solution

  • Having inspected gradle-conventions-1.0.jar, it seems that the custom task class belongs to the default package, so I can register the task as follows:

    project/build.gradle

    plugins {                                                                       
      id 'com.example.my-conventions' version '1.0'
    }
    
    tasks.register('myCustomTask', CustomTask) {
      // ...
    }
    

    But this only works com.example.my-conventions.gradle contains groovy code besides the class itself, otherwise I get the error:

    An exception occurred applying plugin request [id: 'com.example.my-conventions', version: '1.0']
    > Failed to apply plugin 'com.example.my-conventions'.
       > java.lang.ClassNotFoundException: precompiled_ComExampleMyConventions
    

    This approach avoids relying on the buildscript mechanism (which is not recommended in the Gradle documentation).