Is there a way to filter only specific files while building a zip archive?


Still new with Gradle. I am using the Zip type to build an archive. I need to filter some files as I go (i.e. replace some tokens). I didn’t think I would need to specify what kind of files would need to be filtered as I assumed that the tokens, surrounded by an “@@” pair would not be found in any other files (particularly the jar files). However, in my final zip archive, my jar files end up being corrupted. There is no problem if I comment out the filter line. This is my code so far:

task build_patch(type: Zip) {
  archiveName = ''
  from 'contents'
          tokens: [version_number: '2.3', patch_number: '1'])

I need to be able to apply the filter only on some files (txt, sql, xml) but not on others (plb, class, jar).

I will continue experimenting and try to see how I can use includes in the Zip task, maybe I can manage to add several file sets and apply the filter only on one fileset. I have had no luck so far but will continue researching. In the meantime, does someone know the best way to achieve this “partial” filtering while building an archive? I can’t find a good way to do this. I am going t

I was not able to understand how I could add several file sets coming form the same folder, some having a filter, some not, to my Zip archive. So for now, I have resolved to what I have been doing in other contexts: stop trying to do everything in one elegant shot, but process in steps. 1) filter what needs to be filtered while copying it in the zip staging area. 2) zip up the zip staging area.

I am still hoping there is a better way but maybe I’m expecting too much :slight_smile:

from("contents") {
    filter ...

If the ‘from’ is declared elsewhere (e.g. in a Gradle plugin that you can’t change), ‘filesMatching’ should do the trick.

Oh, wow, that seems super simple now that I see the answer, so thank you for that.

I was no able to derive this from the documentation though. Now, that I know what the answer is, I can reverse engineer my way to the solution.

I see that I should have used the

AbstractCopyTask from(Object sourcePath, Closure c)

method on the Zip task, and then should have realized that the Closure was a CopySpec, and thus I could use a combination of includes and filter.

That was not obvious to me, not having a lot of experience using Gradle, Groovy or closures. But thanks to posts like this, I am learning.

Thanks again!