Major feature of Gradle is extensibility. Developer can store common logic in a custom task class.

class GreetingTask extends DefaultTask {
    String greeting = 'hello from Y Soft'

    @TaskAction
    def greet() {
        println greeting
    }
}

task hello(type: GreetingTask)

// Customize the greeting
task greeting(type: GreetingTask) {
    greeting = 'greetings from Brno'
}

It’s not very flexible approach. All classes and the build logic are stored together in one build.gradle file.

It’s possible to move classes into separate Groovy files in buildSrc. Here is the description of transformation process.

Step 1. Create directory buildSrc/main/main/groovy/PACKAGE. E.g.: buildSrc/src/main/groovy/com/ysoft/greeting.

Step 2. Move custom class from build.gradle to GreetingTask.groovy in buildSrc/…/greeting directory.

Step 3. Add package declaration and imports from Gradle API to GreetingTask.groovy.

package com.ysoft.greeting

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

class GreetingTask extends DefaultTask {
    String greeting = 'hello from Y Soft'

    @TaskAction
    def greet() {
        println greeting
    }
}

Step 4. Update build.gradle, add groovy plugin and import of the custom class.

apply plugin: 'groovy'

import com.ysoft.greeting.GreetingTask

task hello(type: GreetingTask)

task greeting(type: GreetingTask) {
    greeting = 'greetings from Brno'
}

Alternatively you can use full package name with class name when specifying task type. In that case you can omit import.

Step 5. Type ‘gradle tasks’ and enjoy.

You can find examples of custom tasks at our GitHub.

Comments