How to exclude all files under a directory which do not match a given criteria


(Derek Andrews) #1

How can I iterate over all of the class files that would be in the jar and exclude some based on criteria? I’ve tried include and exclude with simple * patterns but this is NOT enough. What I need to do is basically say:

“For every class file in a particular package, please exclude any file which is not THIS NAME or does not include THIS STRING in the name.”

My hope was I could iterate over every class file that is going to be in the jar, and then call “exclude” when the above criteria is reached. I looked at the gradle docs and it looks like I should be able to apply a closure to the exclude command itself. For sanity testing, I tried printing out the file name from the exclude closure, expecting an exhaustive list of all class files that would be in the jar, but puzzlingly it was only a handful. I also tried iterating over “source” which the docs say is all the source files for the task. I also tried iterating over the results of the “files” command below. I also tried adding filter, with a closure, to files(sourceSets.main.output.classesDir) to exclude classes that way. I tried printing out file names. Sometimes the prints work, sometimes they don’t. Suffice it to say I’m pretty lost, despite googling for two hours and trying everything I can think of. I’m new to Groovy as well.

task dist(dependsOn: classes, type: Jar) {
from files(sourceSets.main.output.classesDir)
from files(sourceSets.main.output.resourcesDir)
from {configurations.compile.collect {zipTree(it)}}
from files(project.assetsDir);

manifest {
    archiveName = gameArchive + ".jar"
    attributes 'Main-Class': project.mainClassName
}

}


(Derek Andrews) #2

I was able to solve my issue miraculously after posting that. Rubber ducky?

task dist(dependsOn: classes, type: Jar) {
from files(sourceSets.main.output.classesDir)
from files(sourceSets.main.output.resourcesDir)
from {configurations.compile.collect {zipTree(it)}}
from files(project.assetsDir);

exclude { file ->
    if (file.path.contains("com/heh/module")) {
        if (!(file.name.equals("GameModule.class") ||
            file.name.contains(game.capitalize()))) {
            return true
        }
    }
    if (file.path.contains("com/heh/manager/soundtrack")) {
        if (!(file.name.equals("SoundtrackManager.class") ||
                file.name.contains(game.capitalize()))) {
            return true
        }
    }
    if (file.path.contains("com/heh/manager/rastereffect")) {
        if (!(file.name.equals("RasterEffectManager.class") ||
                file.name.contains(game.capitalize()))) {
            return true
        }
    }
    return false
}

manifest {
    archiveName = gameArchive + ".jar"
    attributes 'Main-Class': project.mainClassName
}

}