Search code examples
gradlejartiming

Gradle JAR Creation Timing


i have a gradle build that retrieves properties file and such that are remote (to keep passwords out of github) but the remote retrieval doesn't complete by the time the JAR is built.

i figured i either had to get the JAR created in the execution phase instead of configuration phase or add the remote files in the execution phase but i couldn't get either working.

any suggestions?

task fatJar(type: Jar) {

  doFirst {
    exec {
      executable './scripts/getRemoteResources.sh'
    }
  }

  ...

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) 
  }

  //some resources are retrieved remotely & b/c of timing they don't get included here
  from ('src/main/java/resources') {
    include '*'
  }

  with jar

  //tried this but doesn't work
  //doLast {
  //  jar {
  //    from ('src/main/java/resources') {
  //      include '*'
  //    }
  //  }
  //}


}

Solution

  • You shouldn't use the task graph for this. Also you shouldn't download the file to src/main/

    Instead, you should

    1. Create a task to download the remote resources to a directory under $buildDir (so it's cleaned via the "clean" task)
    2. Configure the TaskOutputs so that the result can be cached and re-used.
    3. Wire the task into Gradle's DAG
    4. Add the directory to the "processResources" task so it ends up on the runtime classpath (ie in the jar)

    Eg:

    tasks.register('remoteResources', Exec) {
       inputs.property('environment', project.property('env')) // this assumes there's a project property named 'env'
       outputs.dir "$buildDir/remoteResources" // point 2 (above)
       commandLine = [
          './scripts/getRemoteResources.sh', 
          '--environment', project.property('env'),
          '--outputdir', "$buildDir/remoteResources"
       ]
       doFirst {
          delete "$buildDir/remoteResources"
          mkdir "$buildDir/remoteResources"
       }
    }
    processResources {
       from tasks.remoteResources // points 3 & 4 (above)
    }
    

    See The Java Plugin - Tasks

    processResources — Copy

    Copies production resources into the production resources directory.