-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathcommand.go
More file actions
37 lines (29 loc) · 775 Bytes
/
command.go
File metadata and controls
37 lines (29 loc) · 775 Bytes
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
package main
import (
"bytes"
"os/exec"
"syscall"
)
// A Command contains the binary executable to be run when executing commands.
type Command struct {
bin string
}
// Exec runs the specified command and returns its output and exit code.
func (c *Command) Exec(cmds ...string) (string, int) {
cmd := exec.Command(c.bin, cmds...)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
code := 1
// Make sure we catch errors and return the correct exit code, if possible
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
code = status.ExitStatus()
}
}
return stderr.String(), code
}
return stdout.String(), 0
}