Exec, standardOutput to file in ${buildDir}, but no ${buildDir} (yet)


(Jeremy) #1

I added the following to an existing project, and everything worked as expected:

task runIt(type:Exec) {
  commandLine "echo", "it works"
  standardOutput new FileOutputStream("${buildDir}/runIt.out")
}

But then I cloned a clean copy of the repo, and the build fails because at configuration phase ${buildDir} hasn’t been created yet. How can the “new” be delayed until execution phase? (Note that commandLine is required at configuration, so you can’t just “<<” it)


(Lance Java) #2

You might need to init the outputstream in the execution phase rather than the configuration phase.

Eg:

task runIt(type:Exec) {
  commandLine "echo", "it works"
  doFirst {
     standardOutput new FileOutputStream("${buildDir}/runIt.out")
  }
}

(Jeremy) #3

Thank you, @Lance_Java - that does solve the problem in my actual project…
But it isn’t quite a complete solution to this toy build. In my real project the Exec task dependsOn a task which ensures ${buildDir} exists. This toy build we have been using to describe the problem needs to

mkdir "${buildDir}"

just prior to the “new” to work (fortunately mkdir is a no-op if the dir already exists).