Search code examples
gradleziplifecycleexecution

gradle zip task only creates zip in configuration phase


When I try to create a zip file in the execution phase of a Zip typed gradle task no zip file is created. If I perform the same in the configuration phase (leaving out the doLast statement), the zip file is created without problems. The doLast block is called since the println statement is shown in the output logging.

The reason that we need to generate the zip in the execution phase is because the file which needs to be compressed is the result of the compile execution. I have also tried to solve this with a jar task, but this gives me similar problems.

Here's the code:

    task createClassPathJar(type: Zip) {
  dependsOn("createManifest")

    from("${projectRoot}") {
        include "MANIFEST.MF"
    }
    archiveName = "dummy.jar"

    doLast {

    destinationDir(file("${projectRoot}"))

    archiveName = "zipfile.jar"

    println "executing phase createClassPathJar. archiveName: " + archiveName
  }
}

Can someone help me here ? I'm using Gradle v6.4.1.


Solution

  • You cannot use doLast to configure the action of your task, because it will be executed after the particular action (in this case the zipping) has run. Either use a doFirst closure or setup your task configuration in a way that it does not depend on other configurations:

    As an example, depending on how properly your task createManifest defines its output, you may use it directly to define the Zip task content using "from createManifest".

    I guess your reason for using a doLast closure is the call to destinationDir that is based on a variable. Instead, you may just use a closure that evaluates the variable lazily:

    task createManifest {
       outputs.file('path/to/MANIFEST.MF')
    }
    
    task createClassPathJar(type: Zip) {
        from createManifest
        archiveName = 'zipfile.jar'
        destinationDir = file({ "${projectRoot}" }) // or just file({ projectRoot })
    }