1

I have a build pipeline where I want to run a particular jar (with some args) after copying it into a separate folder from the dependency list.

Currently I'm doing the following:

task copyToLib(type: Copy, dependsOn: classes) {
    into "$buildDir/server"
    from(configurations.compile) {
        include "webapp-runner*"
    }
    ext.serverPath =  fileTree("$buildDir/server/").include("webapp-runner-*.jar").getSingleFile()
}

task run(type: Exec, dependsOn: [copyToLib, war]) {
    mustRunAfter copyToLib
    executable 'java'
    args '-jar', copyToLib.serverPath, war.archivePath, '--port', "$port"
}

But it fails with Expected directory '...' to contain exactly one file, however, it contains no files. since I'm guessing serverPath is set during config phase when the file has not been copied. How do I get around this?

user3690467
  • 3,049
  • 6
  • 27
  • 54

1 Answers1

1

You are falling for the common mistake of executing logic in the configuration phase when you should be executing it in the execution phase.

Try this

task copyToLib(type: Copy, dependsOn: classes) {
    ...
    doLast {
        ext.serverPath = ...
    }
}

If it were me, I'd calculate serverPath inside run rather than in copyToLib. Perhaps you could use a closure to delay the calculation.

Eg:

task run(type: Exec, dependsOn: [copyToLib, war]) {
    def pathClosure = {
        fileTree("$buildDir/server/").include("webapp-runner-*.jar").singleFile
    }
    mustRunAfter copyToLib
    executable 'java'
    args '-jar', pathClosure, war.archivePath, '--port', "$port"
}
lance-java
  • 25,497
  • 4
  • 59
  • 101
  • I tried this but then my run task complains that the property does not exist (probably since `args` runs in configuration phase) – user3690467 Aug 15 '17 at 11:04
  • Error: Unable to access jarfile build_6ya3c8i4opyc4ki50kxakvuxg$_run_closure7$_closure13@61f7c533 – user3690467 Aug 15 '17 at 11:22
  • Looks like `args` doesn't support closures (it just calls `toString()` on each arg). You'll need to invoke `project.exec(...)` in a `doLast { ... }` rather than using an `Exec` task. You should raise a ticket on the gradle project for `args` to support `closures` – lance-java Aug 15 '17 at 11:25
  • Working now with: `doLast { project.exec({ commandLine = ['java', '-jar', copyToLib.serverPath(), war.archivePath, '--port', "$port"] }) }` – user3690467 Aug 15 '17 at 11:36