Gradle JAR 创建时间

Gradle JAR Creation Timing

我有一个 gradle 构建可以检索属性文件等远程文件(将密码保存在 github 之外)但是远程检索在构建 JAR 时还没有完成.

我想我要么必须在执行阶段而不是配置阶段创建 JAR,要么在执行阶段添加远程文件,但我无法工作。

有什么建议吗?

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 '*'
  //    }
  //  }
  //}


}

这似乎可行,所以我将继续使用它,除非有人有更好的解决方案...

gradle.taskGraph.beforeTask { Task task ->

  println "just before $task.name"

  // i just chose to kick this off with the first task sent through here
  if (task.name=="compileJava") {
    exec {
      executable './scripts/getRemoteResources.sh'
    }
  }
}
      


task fatJar(type: Jar) {

  ...

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

  from ('src/main/java/resources') {
    include '*'
  }

  with jar

}

您不应该为此使用任务图。此外,您不应将文件下载到 src/main/

相反,您应该

  1. 创建一个任务,将远程资源下载到 $buildDir 下的目录中(因此它通过“clean”任务清理)
  2. 配置 TaskOutputs 以便可以缓存和重新使用结果。
  3. 将任务连接到 Gradle 的 DAG
  4. 将目录添加到“processResources”任务,使其在运行时类路径(即在 jar 中)结束

例如:

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)
}

The Java Plugin - Tasks

processResources — Copy

Copies production resources into the production resources directory.