Search code examples
gradlezip

Reconstructing file structure in ZIP file from list of strings


This is probably a lot easier than I am making it. I have a string list of files, with their relative locations, in the current project, dynamically generated, which we want to add to a zip file. I currently have the following code:

task sourceDrop(type: Zip) {
    def filelist = getFileList()
    
    baseName = "sourceDrop"
    version = "1.0"
    filelist.each {
        from it // adds every single file to the archive
    }
    destinationDir = new File(rootProject.projectDir, "")
}

It's creating a zip file with every item in it as a flat structure, no folders. Is there an elegant way to say "keep the relative paths"?


Solution

  • Working example here.

    Consider this task:

    task sourceDrop(type: Zip) {
        def filelist = getFileList() 
     
        baseName = "sourceDrop"
        version = "1.0"
        
        fileList.each { file ->
            def info = getFileInfo(file)
            from (info.relativeDir) {
                include info.filename into info.relativeDir
            }
        }
    
        destinationDir = new File(rootProject.projectDir, "")
    }
    

    Note that getFileInfo() is a home-grown method that splits a relative path into the path and file name.