Handling Output from External Programs

Powerful Command-Line Applications in Go — by Ricardo Gerardi (65 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding Another Step to the Pipe line | TOC | Running Commands with Contexts 👉

The two external programs you’ve executed are well-behaved; if something goes wrong, they return an error that you can capture and use to make decisions. Unfortunately, not all programs work like that.

In some cases, the program exits with a successful return code even when something goes wrong. In these cases a message in STDOUT or STDERR generally provides details about the error condition. In other cases, a program completes successfully as designed but something on its output tells you that the condition represents an error.

When executing external programs in Go you can handle both of these scenarios by capturing the program’s output and parsing it to make decisions.

The next step in the pipeline is the execution of the gofmt tool to validate whether the target project conforms to the Go code formatting standards or not. The gofmt tool doesn’t return an error. Its default behavior is to print the properly formatted version of the Go program to STDOUT. Typically, users run gofmt with the -w option to overwrite the original file with the correctly formatted version. But in this case, you only want to verify the program and validate the formatting as part of the CI pipeline. You can use the -l option which returns the name of the file if the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.