Search

Dark theme | Light theme

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 app.properties in the directory src/main/resources we can run the task $ gradle processResources and the file is copied to build/classes/main/app.properties. 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:

import org.apache.tools.ant.filters.*

apply plugin: 'java'

version = '1.0-DEVELOPMENT'

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

def allProcessResourcesTasks() {
    sourceSets.all.processResourcesTaskName.collect {
        tasks[it]
    }
}

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

# src/main/resources/app.properties
appversion=@version@
# src/test/resources/test.properties
gradleVersion=@gradleVersion@

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

$ gradle build
:compileJava
:processResources
:classes
:jar
:assemble
:compileTestJava
:processTestResources
:testClasses
:test
:check
:build

BUILD SUCCESSFUL

Total time: 4.905 secs

$ cat build/classes/main/app.properties 
appversion=1.0-DEVELOPMENT
$ cat build/classes/test/test.properties 
gradleVersion=0.9-rc-2

Written with Gradle 0.9.