-
Notifications
You must be signed in to change notification settings - Fork 3
/
exec.go
61 lines (56 loc) · 1.82 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
53
54
55
56
57
58
59
60
61
package main
import (
"bytes"
"io"
"os"
"os/exec"
"github.com/pkg/errors"
)
// capture executes the command specified by args and returns its stdout. If
// the process exits with a failing exit code, capture instead returns an error
// which includes the process's stderr.
func capture(args ...string) (string, error) {
var cmd *exec.Cmd
if len(args) == 0 {
panic("capture called with no arguments")
} else if len(args) == 1 {
cmd = exec.Command(args[0])
} else {
cmd = exec.Command(args[0], args[1:]...)
}
out, err := cmd.Output()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
err = errors.Errorf("%s: %s", err, exitErr.Stderr)
}
return "", err
}
return string(bytes.TrimSpace(out)), err
}
// spawn executes the command specified by args. The subprocess inherits the
// current processes's stdin, stdout, and stderr streams. If the process exits
// with a failing exit code, run returns a generic "process exited with
// status..." error, as the process has likely written an error message to
// stderr.
func spawn(args ...string) error {
return spawnWith(os.Stdin, os.Stdout, os.Stderr, args...)
}
// spawnWith executes the command specified by args using the provided reader
// and writers for process I/O. The subprocess inherits the current processes's
// stdin, stdout, and stderr streams. If the process exits with a failing exit
// code, run returns a generic "process exited with status..." error, as the
// process has likely written an error message to stderr.
func spawnWith(in io.Reader, out, err io.Writer, args ...string) error {
var cmd *exec.Cmd
if len(args) == 0 {
panic("spawn called with no arguments")
} else if len(args) == 1 {
cmd = exec.Command(args[0])
} else {
cmd = exec.Command(args[0], args[1:]...)
}
cmd.Stdin = in
cmd.Stdout = out
cmd.Stderr = err
return cmd.Run()
}