How can I manipulate a ProcessResources task so that it honors excludes properly?

Hi guys!

I have a project with several source sets, all containing resources. Within these resources are files with the suffix ‘.utf8’. What I want is to filter these files during resource processing and replace all non-ascii characters with the escaped unicode version (as in ant.native2ascii). I also want to rename these files after the process by cutting of the ‘.utf8’ suffix. I finally came up with this code:

project.sourceSets.each { s ->
    project.tasks.getByName(s.processResourcesTaskName) { task ->
        task.from(s.resources.srcDirs) {
            include '**/*.utf8'
            filter(EscapeUnicode)
            rename '(.*).utf8', '$1'
        }
        task.from(s.resources.srcDirs) {
            exclude '**/*.utf8'
        }
        task.doLast {
            FileTree tree = fileTree (dir: task.destinationDir);
            tree = tree.matching {
                include '**/*.utf8'
            }
            tree.each { File file ->
                delete(file)
            }
        }
    }
}

I would like to get rid of the doLast block. I though that my exclude block would be enough, but unfortunately that’s not true. If I remove the doLast block, I am ending up with the proper filtered file together with an unfiltered ‘.utf8’ version of the file side by side. The exclude block simply doesn’t work. I tried this solution declarative with one of my resource tasks and in this case, the exclude block is honored. So the problem is prolly that I am already in the execution phase?

So my question: What’s a better way to do this without declaring the same block of code for every of my resource tasks?

The problem with your code is that it adds further copy actions on top of the existing ones. Instead try something like:

tasks.withType(ProcessResources) {
    filesMatching("**/*.utf8") {
        filter(EscapeUnicode)
        name = name[0..-6]
    }
}