-
Notifications
You must be signed in to change notification settings - Fork 152
/
exec.go
52 lines (48 loc) · 1.57 KB
/
exec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package exec
import (
"errors"
"fmt"
"os/exec"
)
// ExitError is an error type that is produced by the Exec() function when a
// command returns a non-zero exit code.
type ExitError struct {
// Command is the command that caused the error.
Command string
// Output is the combined output (stdout and stderr) produced when Command was
// executed.
Output []byte
// ExitCode is the exit code that was returned when Command was executed.
ExitCode int
}
func (e *ExitError) Error() string {
return fmt.Sprintf(
"error executing cmd [%s]: %s",
e.Command,
string(e.Output),
)
}
// Exec is a custom replacement for cmd.CombinedOutput(). It executes the
// provided command and returns the command's combined output (stdout + stderr)
// and an error. When the command completes successfully, with a non-zero exit
// code, the error is nil. If the command's exit code is non-zero, the error is
// of type ExitError. Other, unanticipated errors are wrapped and returned
// as-is. The primary benefit to calling Exec() over calling
// cmd.CombinedOutput() directly is that errors will automatically include
// command output, which is likely to contain important information about the
// cause of the error.
func Exec(cmd *exec.Cmd) ([]byte, error) {
res, err := cmd.CombinedOutput()
var exitErr *exec.ExitError
if ok := errors.As(err, &exitErr); ok {
return res, &ExitError{
Command: cmd.String(),
Output: res,
ExitCode: exitErr.ExitCode(),
}
}
if err != nil {
err = fmt.Errorf("error executing cmd [%s]: %s: %w", cmd.String(), string(res), err)
}
return res, err
}