Friday, October 15, 2010

Gradle Goodness: Automatic Clean Tasks

Gradle adds the task rule clean<Taskname> to our projects when we apply the base plugin. This task is able to remove any output files or directories we have defined for our task. For example we can assign an output file or directory to our task with the outputs property. Or we can use the @OutputFile and @OutputDirectories annotations for custom task classes. The clean<Taskname> rule can delete the output files or directories for the task with the name <Taskname> for us. We don't have to write the clean task ourselves we only have define the base plugin in our project. And Gradle will take care of the rest!.

apply plugin: 'base'

outputDir = file("$buildDir/generated-src")
outputFile = file("$buildDir/output.txt")

task generate << {
    outputFile.write 'Generated by Gradle.'
generate.outputs.files outputFile
generate.outputs.dir outputDir

task showBuildDir << {
    def files = buildDir.listFiles()
    files.each {
        print   it.directory ? 'Dir:  ' : 'File: '
        println it.name
    println "${files.size()} files in $buildDir.name"

We can first run the generate task and see the output file and directory.

$ gradle -q generate showBuildDir
Dir:  generated-src
File: output.txt
2 files in build

Next we can run the task cleanGenerate, which is added to the project by Gradle, and see the output files are gone.

$ gradle -q cleanGenerate showBuildDir
0 files in build


Anonymous said...

Kan you explain how and what the other task in the base plugging works and what they do. Im trying to write a build script for a C# project but find no good documentatin on the base pluggin.

I like you blog lots of good info

mrhaki said...

@Anonymous: You can read more at http://mrhaki.blogspot.com/2010/10/gradle-goodness-base-plugin-usage.html

Bruce Edge said...

Does this not work in gradle 1.7?

FAILURE: Could not determine which tasks to execute.

* What went wrong:
Task 'generateClean' not found in root project 'clean'.

* Try:
Run gradle tasks to get a list of available tasks.

There's no cleanGenerate listed in the gradle tasks output.

Post a Comment