Using Groovy, how can I capture the console output (System.out
and System.err
) of a shell command that runs another process?
In practice, I am running prettier
using yarn
and trying to capture the output of both processes as it is seen if I were to run the yarn
command in my shell.
Running yarn prettier --check .
yields
yarn run v1.22.17
$ /my-project/node_modules/.bin/prettier --check .
Checking formatting...
[warn] some-file.ts
[warn] another-file.ts
[warn] Code style issues found in 2 files. Run Prettier with --write to fix.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
which is the output I would like to capture. However, the Groovy code
def check = "yarn prettier --check .".execute()
check.waitFor()
println check.getText()
yields only
yarn run v1.22.17
$ /my-project/node_modules/.bin/prettier --check .
Checking formatting...
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
which is missing Prettier's output. To me, this looks like Groovy is only capturing the output of the Yarn process and not the Prettier process that is spawned by Yarn.
Is it possible to capture the missing output from Prettier as well? I realize I could run Prettier directly from Groovy but would like to avoid that due to other configuration.
So if prettier is writing to standard err you would not get that using Process.getText(). So you might try adjusting a little bit to this:
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = "yarn prettier --check frontend-angular/projects/admin".execute()
proc.consumeProcessOutput(sout, serr)
proc.waitFor()
println( sout )
println( serr )
See if that captures both processes output. Other than that I think you may have to run it separately.