ensure/exec/main.go

44 lines
974 B
Go

package exec
// exec is a small package to provide a wrapper around Cmd from os/exec to
// fulfill the Ensurer interface.
import (
"bytes"
"fmt"
"io"
"os/exec"
)
type (
// E is a wrapper around Cmd from os/exec to fulfill Ensurer.
E exec.Cmd
)
// Ensure runs the command in the current context.
func (e *E) Ensure() error {
var (
stdout io.ReadWriter
stderr io.ReadWriter
)
if e.Stdout == nil {
stdout = bytes.NewBuffer([]byte{})
e.Stdout = stdout
}
if e.Stderr == nil {
stderr = bytes.NewBuffer([]byte{})
e.Stderr = stderr
}
cmd := (*exec.Cmd)(e)
if err := cmd.Start(); err != nil {
return fmt.Errorf("could not run command: %w", err)
}
err := cmd.Wait()
if procState, ok := err.(*exec.ExitError); ok && procState.ExitCode() > 0 {
fmt.Printf("could not run command: %s\nstdout: %s\nstderr: %s\n", err, stdout, stderr)
return fmt.Errorf("error when calling command: %s", err)
}
return fmt.Errorf("could not run command: %s", err)
}