George Karanikas
George Karanikas

Reputation: 1244

Custom Task/Plugin in gradle

I'm trying to create a custom Task/Plugin (both refuse to work) to use in my gradle build script.

I'm using the groovy plugin and want to declare the Tasks/Plugins in a separate files and not inside my build.gradle.

My project tree is the following:

/project
.
|-gradle
|-src
|---main
|-----groovy
|-----java
|-----resources
|---test
|-----groovy
|-----java
|-----resources
|-build.gradle

What I tried to do, is create my Task/Plugin classes inside src/main/groovy and then use them in my build.gradle.

Let me give a small example.

src/main/groovy/mypackage/TestTask.groovy:

package org.gradle.mypackage

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

public class TestTask extends DefaultTask {

    @TaskAction
    def doAction() {

    }
}

build.gradle

plugins {
    id 'groovy'
}

sourceCompatibility = 1.7

repositories {
    mavenCentral()
}

dependencies {

    compile(
        localGroovy(),
        gradleApi()
    )

    testCompile(
        [ group: 'junit', name: 'junit', version: '4.11' ]
    )

}

task testTask(type: TestTask)

When I try to do anything using my gradle.build (clean, build, etc), I get the following error:

Error:(116, 0) Could not find property 'TestTask' on root project 'project'.

What am I doing wrong? I tried to import the Task in build.gradle using import mypackage.TestTask but that didn't work either.

It looks to me like the groovy files do not compile at all while from what I read in the docs gradle should take care of compiling and adding them in the classpath.

Upvotes: 2

Views: 2415

Answers (2)

charlie_pl
charlie_pl

Reputation: 3094

Here you go: "in-stackoverflow" solution.

In your project create folder buildSrc/src/main

Don't forget to create build.gradle in buildSrc/

apply plugin: 'groovy'

dependencies {
    compile gradleApi()
    compile localGroovy()
}

Now in the main folder create package with your task, for example: pl.myAwesomeCompany.gradle.tasks

package pl.myAwesomeCompany.gradle.tasks

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.incremental.IncrementalTaskInputs

class ExampleTask extends DefaultTask {

    @TaskAction
    void execute(IncrementalTaskInputs inputs) {
        println inputs.incremental ? "CHANGED inputs considered out of date"
            : "ALL inputs considered out of date"
    }
}

Voila! Now in your project you can use your plugin:

import package pl.myAwesomeCompany.gradle.tasks.ExampleTask
task incremental(type:ExampleTask)

Upvotes: 2

Opal
Opal

Reputation: 84854

This is not how it works. If you need to provide custom plugins and tasks organized in packages , put the whole code under buildSrc directory. Under $GRADLE_HOME/samples/multiProjectBuildSrc You can find excellent example how it should be done.

$GRADLE_HOME - gradle installation directory.

Upvotes: 0

Related Questions