gradle processResources with different replacement

2019-06-11 10:26发布

问题:

I'd love to filter specific java resources in my gradle project. Where some files should have replaced contents only, some should be also renamed (and have different content replaced).

My gradle java project setup is:

> cat build.gradle 
apply plugin: 'java'
sourceSets {
    main {
        java { 
            resources { 
                srcDirs = [ "foo" ]
                include '**/**'
            } 
        }       
    }
}

processResources {
    include '**/file_a.txt'
    filter { String line ->
        line
            .replace("foo", "fool" )
        }   
}


processResources {
    include '**/file_b.txt'
    rename { "file_c.txt" }
    filter { String line ->
        line
            .replace("ipsum", "zzz" )
        }   
}                                        

> cat foo/file_a.txt 
my name is foo
test ipsum 

> cat foo/file_b.txt
lorem ipsum ...

Once running:

gradle build

I get:

> ls build/resources/main 
file_c.txt

> cat build/resources/main/file_c.txt
my name is fool
test zzz

However I'd like to get both files, where only file_b.txt would be renamed and both would be replaced by the specific rules. What is the proper way to achieve that?

回答1:

OK, found the solution myself, following seems to be working as expected:

apply plugin: 'java'
sourceSets {
    main {
        java { 
            resources { 
                srcDirs = [ "foo" ]
                include '**/**'
                exclude '**/*.txt'
            } 
        }       
    }
}

processResources {
    with copySpec {
        from 'foo/file_a.txt'
        filter { String line ->
            line
                .replace("foo", "fool" )
            }   
    }

    with copySpec {
        from 'foo/file_b.txt'
        rename { "file_c.txt" }
        filter { String line ->
            line
                .replace("ipsum", "zzz" )
            }   
    }
}


回答2:

I, personally, think that resources and filtered resources should be kept separate. Ie src/main/resources and src/main/filteredResources. I also thing you should avoid excludes (eg exclude '**/*.txt') resources and filteredResources directories should contain ONLY what will end up in the jar... NOTHING ELSE

import org.apache.tools.ant.filters.ReplaceTokens

processResources {
    with copySpec {
        from 'src/main/filteredResources'
        filter(ReplaceTokens, tokens: [foo: 'fool', ipsum: 'zzz'])
    }
}

The above snippet will replace @foo@ and @ipsum@ in ALL files in the src/main/filteredResources folder



标签: java gradle