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

  • THIS WORKS!!

    Suggested by Simon, I finally fix it

    buildSrc/build.gradle

    plugins {
        id 'groovy' // Groovy or Kotlin can also be used
    }
    

    And a groovy file like this

    buildSrc/src/main/groovy/MyTask3.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
    

    Then in other build file I use the task

    subproject/build.gradle

    task myTaskThree(type: MyTask3) {
        dependsOn(clean)
        name = "Jonh Doe"
    }
    compileJava.dependsOn myTaskThree
    

    Thanks !