Search

Dark theme | Light theme

October 14, 2010

Gradle Goodness: Add Incremental Build Support to Custom Tasks with Annotations

In a previous post we learned how we can use the inputs and outputs properties to set properties or files that need to be checked to see if a task is up to date. In this post we learn how a custom task class can use annotations to set input properties, file or files and output files or dir.

For input we can use @Input, @InputFile, @InputFiles or @InputDirectory annotations. Gradle uses the properties with annotations for checking if a task is up to date. Output file or directory can be marked with @OutputFile and @OutputDirectory.

task generateVersionFile(type: Generate) {
    version = '2.0'
    outputFile = file("$project.buildDir/version.txt")
}

task showContents << {
    println generateVersionFile.outputFile.text
}
showContents.dependsOn generateVersionFile

class Generate extends DefaultTask {
    @Input
    String version

    @OutputFile
    File outputFile

    @TaskAction
    void generate() {
        def file = getOutputFile()
        if (!file.isFile()) {
            file.parentFile.mkdirs()
            file.createNewFile()
        }
        file.write "Version: ${getVersion()}"
    }
}

We can run our task and get the following output:

$ gradle showContents
:generateVersionFile
:showContents
Version: 2.0

BUILD SUCCESSFUL

And if we run it again we see the task is now up to date:

$ gradle showContents
:generateVersionFile UP-TO-DATE
:showContents
Version: 2.0

BUILD SUCCESSFUL

We can change the version numer in our build script to 2.1 and see the output:

$ gradle showContents
:generateVersionFile
:showContents
Version: 2.1

BUILD SUCCESSFUL

Written with Gradle 0.9.