javagradle

Include a task definition into an external gradle file


I've look to a similar question here Extract common methods from Gradle build script

And it works for methods. But I want to externalize a class that will act a a task definition.

mytask.gradle

    class doSomethingTask extends DefaultTask {
        @Input
        String someData

        @TaskAction
        void taskAction() {

build.gradle

    apply from mytask.gradle
    task doSomething(type: doSomethingTask) {
        dependsOn(clean, build)
        someData = "$mydata"
    }

And doSomethingTask is not found in build.gradle, build doesn't work.

How can I fix this ? Is there a method to export the class definition (like ext { tasks.mydef = ... ) ? Or is there another way.

Real task code is bigger and I don't want to polute my gradle build.

NEW EDIT

Suggested by Simon, I make a file like this

buildSrc/build.gradle
plugins {
    id 'groovy' // Groovy or Kotlin can also be used
}

tasks.register('myTask3', MyTask3.class)

And a groovy file like this

buildSrc/src/main/groovy/MyTaks3.groovy
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Input


class MyTask3 extends DefaultTask {
    @Input String name

    @TaskAction
    void taskAction(){
        //Something

But it gives me errors, like

A problem occurred evaluating project ':buildSrc'.
> Could not get unknown property 'PostProcessOpenApiCodeTask3' for project ':buildSrc' of type org.gradle.api.Project.

I've tried several combinations but nothing seems to work, also search for examples with no luck...

I'm using an old gradle, 5.5, so documentation is scarce.

If anyone could help...

Thanks


Solution

  • buildSrc folder

    Probably the easiest way to give a build script access to such a class is to put it in a buildSrc subproject. This is a default "included build" whose outputs are made available to build scripts in the same project.

    To do this, add a folder buildSrc under your main project folder with a build.gradle file:

    plugins {
        id 'java' // Groovy or Kotlin can also be used
    }
    
    dependencies {
        compileOnly gradleApi() // For the Gradle classes your class depends on
    }
    

    Then place whatever Java code you want to be compiled and made available to your build scripts in buildSrc/src/main/java as for a regular Java project.

    Other possibilities

    There are two other possibilities if you want the code to sit entirely outside your project.