0

I want to create a task that will zip up all the files in a directory, ignoring all subdirectories. At the same time, I want to iterate through all the subdirectories and create zips that include the files in those directories (and ignoring any further subdirectories).

Thus, for this directory structure, I want the following zips:

$ls build/dirA
fileA
dirB

$ls build/dirA/dirB
fileB

I should get zip/zipA containing fileA, zip/zipB containing fileB.

I am using code based on the answer here: gradle task to zip multiple directories independently Essentially, I create a zip task for each zip artifact to be created, with a dependency on the top level task.

task myZip() {
    file('build').eachDir { dir ->
        dir.eachDir { sub ->
            dependsOn tasks.create("zip$sub.name", Zip) {
                from sub
                baseName sub.name
                destinationDir file('zip')
            }
        }

        dependsOn tasks.create("zip$dir.name", Zip) {
            from dir
            baseName dir.name
            excludes ['*/**']
            destinationDir file('zip')
        }
    }
}

The problem seems to be in the exclude pattern. I get the correct zips for the sub directories, but the parent directory includes fileA and dirB/fileB.

What is the correct way to do this please?

*Note I have not put an exclude for the iteration through the subdirectories, as I figure this pattern needs to be the same as for the parent directory, which I haven't figured out yet.

John
  • 10,837
  • 17
  • 78
  • 141

1 Answers1

1

You can try below script, it would resolve your issue:

import static groovy.io.FileType.DIRECTORIES
task myZip {
    file('folder').traverse(type: DIRECTORIES) {
        def path = it.path
        def zipFile = it.name + '.zip'
        ant.zip(destfile: zipFile){
          fileset(dir: path) {
            include (name: "*")
            type (type: "file")
          }
        }
    }

    doLast {
      copy {
        from "."
        include "*.zip"
        into file("zip")
      }
    }
}

Here is some example test:

$ tree folder
folder
└── dirA
    ├── dirB
    │   ├── dirC
    │   │   ├── dirD
    │   │   └── fileC
    │   └── fileB
    └── fileA

4 directories, 3 files

And it generate the three zip files into zip folder as well as root folder.

$ ls -1 zip/
dirA.zip
dirB.zip
dirC.zip
chenrui
  • 8,910
  • 3
  • 33
  • 43