Files - pford68/gradle-examples GitHub Wiki

Copying Files

TBD

Filtering while copying

This refers to altering the files (e.g., replacing a placeholder) in files while copying. We use the filter() method to define a filter. We can also reuse the Ant filtering classes from the org.apache.tools.ant.filters package for the actual filters.

We can define the filtering class (e.g., ReplaceTokens from the ant.filters package) and can pass parameters for the filter. Or we can pass a closure which is passed each line as an argument. The closure we must return the filtered line.

import org.apache.tools.ant.filters.*
 
task('filterCopy', type: Copy) {
    from 'src/templates'
    into buildDir
    include '**/*.txt'

    // This will replace any line that does not contain "Gradle."
    filter { line -> line.contains('Gradle') ? line : '' } 
    // This will replace @author@ and @gradleVersion@ with the value.
    filter(ReplaceTokens, tokens: [author: 'mrhaki', gradleVersion: gradle.gradleVersion]) 
    // This will prepend the content of header.txt to the file.
    filter(ConcatFilter, prepend: file('src/include/header.txt'))  
}

References