Zipping directory with similar structure

I have the following file structure where under each parent (dirA) has the same folder structure (subDir1, subDir2, subDir3) but not necessarily same # of files under each subdirectory.

dirA
-> subdir1
     -> fileA11
	 -> fileA12
	 -> fileA13
-> subdir2
     -> fileA21
	 -> fileA22
	 -> fileA23
-> subdir3
     -> fileA31
	 -> fileA32
	 -> fileA33

dirB
-> subdir1
     -> fileB11
	 -> fileB12
-> subdir2
     -> fileB21
	 -> fileB23
-> subdir3
	 -> fileB33

What I want to do is zip up the directory for each dirA.zip, dirB.zip, dirC.zip, etc.

So far, I’ve just done brute force:

task copyDirA (type: Zip) {
    archiveName = "dirA.zip"
    destinationDir = file("${buildDir}/dist")

    from ('dirA/subdir1') {
        into 'subdir1'
    }
    from ('dirA/subdir2') {
        into 'subdir2'
    }
    from ('dirA/subdir3') {
        into 'subdir3'
    }
}

// Same above for copyDirB …

There has got to be a more elegant way.

:wink:

Hopefully this gives you some ideas to build on:

def zips = ['dirA', 'dirB']
def subdirs = ['subdir1', 'subdir2', subdir3']

zips.each { dir ->
    tasks.create( "copy${dir.capitalize()}", Zip ) {
        archiveName = "${dir}.zip"
        destinationDir = file( "${buildDir}/dist" )
        subdirs.each { subdir ->
            from( "${dir}/${subdir}" ) {
                into subdir
            }
        }
    }
}

If there’s nothing more than the subdirs in each of the dirs, then you could just use from dir instead of from( ... ) { into ... }.

1 Like