Gradle has excellent incremental build support. This means that Gradle can determine if a task needs to be executed based on the input and output of that task. If for example nothing changed in one of the input and output files, then the task can be skipped. We can add incremental build support for our custom tasks by defining the input and output of the task. We can also define that a task can be skipped when a collection of files or a directory that is the input of the task are empty or not exists. Gradle offers the @SkipWhenEmpty annotation we can apply on the input of our task.

In the next example we have a task DisplayTask that prints the contents of files in a directory. We want to skip the task when the directory is empty.

task display(type:DisplayTask) {
    contentDir = file('src/content')
}

class DisplayTask extends DefaultTask {

    @SkipWhenEmpty
    @InputDirectory
    File contentDir

    DisplayTask() {
        description = 'Show contents of files'
    }

    @TaskAction
    void printMessages() {
        contentDir.eachFile { file ->
            println file.text
        }
    }
}

When we run the task without any files in the input directory we see in the output NO-SOURCE for our task. If we wouldn’t have added the @SkipWhenEmpty annotation the build would have failed.

$ gradle display
:display NO-SOURCE

BUILD SUCCESSFUL

Total time: 0.866 secs

Let’s add a file in the directory src/content and re-run the task:

$ gradle display
:display
Gradle rocks!


BUILD SUCCESSFUL

Total time: 0.866 secs

Written with Gradle 3.4.

shadow-left