November 5, 2010

Gradle Goodness: Add Filtering to ProcessResources Tasks

When we apply the Java plugin (or any dependent plugin like the Groovy plugin) we get new tasks in our project to copy resources from the source directory to the classes directory. So if we have a file in the directory src/main/resources we can run the task $ gradle processResources and the file is copied to build/classes/main/ But what if we want to apply for example some filtering while the file is copied? Or if we want to rename the file? How we can configure the processResources task?

The task itself is just an implementation of the Copy task. This means we can use all the configuration options from the Copy task. And that includes filtering and renaming the files. So we need to find all tasks in our project that copy resources and then add for example filtering to the configuration. The following build script shows how we can do this:


apply plugin: 'java'

version = '1.0-DEVELOPMENT'

afterEvaluate {
    configure(allProcessResourcesTasks()) {
               tokens: [version: project.version, gradleVersion: project.gradle.gradleVersion])

def allProcessResourcesTasks() {
    sourceSets.all.processResourcesTaskName.collect {

Let's create the following two files in our project directory:

# src/main/resources/
# src/test/resources/

We can now execute the build and look at the contents of the copied property files:

$ gradle build


Total time: 4.905 secs

$ cat build/classes/main/ 
$ cat build/classes/test/