How to create custom gradle task type and not have to specify full path to type in build.gradle?


(Eric Deandrea) #1

So I’ve created a custom type - call it whatever you want. In this example the class is called com.mycompany.gradle.build.types.SomeBuildType. This class extends Gradle’s org.gradle.api.DefaultTask class. Now in my build.gradle file I create one or more tasks of this type like this:

task someTaskOfMyType(type: com.mycompany.gradle.build.types.SomeBuildType) {
   ...
}

My question is this - is there a way I can ship my types so that users don’t have to specify the fully-qualified classname as the type, so that they could do something like this?

task someTaskOfMyType(type: SomeBuildType) {
  ...
}

I am shipping a custom distribution and I already know about the way to package plugins so they can be referenced like this

apply plugin: 'mycompany-pluginName'

(Rolf Suurd) #2

You can add imports to gradle scripts. However, your users will have to do this themselves. The reason you don’t have to do this for gradle tasks is because gradle scripts obtain a bunch of imports from default-imports.txt and i don’t think it’s currently possible to add to those import statements just yet.


(Eric Deandrea) #3

Since I’m creating/packaging/shipping my own custom distribution - is there a way i could add my own imports somewhere into a .gradle file similar to how gradle is doing it?

Do you know where the default-imports.txt file lives within the gradle distro?


(Luke Daley) #4

The default imports are defined by a file that is in the gradle-core jar @ ‘org/gradle/configuration/default-imports.txt’. This is not user extensible, so you’d have to pull gradle-core apart, modify the file and then repack it.

Another option is to fake it by create an extra property that is the task class object in the plugin…

class MyPlugin implements Plugin {
  void apply(project) {
    project.ext.SomeBuildType = com.mycompany.gradle.build.types.SomeBuildType
  }
}

It’s a bit hacky, but it works.


(Eric Deandrea) #5

This does work. Thanks!