-
Notifications
You must be signed in to change notification settings - Fork 37
/
exec_cmd_runner.go
94 lines (71 loc) · 2.08 KB
/
exec_cmd_runner.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package system
import (
"os"
"os/exec"
"runtime"
"strings"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
type execCmdRunner struct {
logger boshlog.Logger
}
func NewExecCmdRunner(logger boshlog.Logger) CmdRunner {
return execCmdRunner{logger}
}
func (r execCmdRunner) RunComplexCommand(cmd Command) (string, string, int, error) {
process := NewExecProcess(r.buildComplexCommand(cmd), cmd.KeepAttached, cmd.Quiet, r.logger)
err := process.Start()
if err != nil {
return "", "", -1, err
}
result := <-process.Wait()
return result.Stdout, result.Stderr, result.ExitStatus, result.Error
}
func (r execCmdRunner) RunComplexCommandAsync(cmd Command) (Process, error) {
process := NewExecProcess(r.buildComplexCommand(cmd), cmd.KeepAttached, cmd.Quiet, r.logger)
err := process.Start()
if err != nil {
return nil, err
}
return process, nil
}
func (r execCmdRunner) RunCommand(cmdName string, args ...string) (string, string, int, error) {
return r.RunComplexCommand(Command{Name: cmdName, Args: args})
}
func (r execCmdRunner) RunCommandQuietly(cmdName string, args ...string) (string, string, int, error) {
return r.RunComplexCommand(Command{Name: cmdName, Args: args, Quiet: true})
}
func (r execCmdRunner) RunCommandWithInput(input, cmdName string, args ...string) (string, string, int, error) {
cmd := Command{
Name: cmdName,
Args: args,
Stdin: strings.NewReader(input),
}
return r.RunComplexCommand(cmd)
}
func (r execCmdRunner) CommandExists(cmdName string) bool {
_, err := exec.LookPath(cmdName)
return err == nil
}
func (r execCmdRunner) buildComplexCommand(cmd Command) *exec.Cmd {
execCmd := newExecCmd(cmd.Name, cmd.Args...)
if cmd.Stdin != nil {
execCmd.Stdin = cmd.Stdin
}
if cmd.Stdout != nil {
execCmd.Stdout = cmd.Stdout
}
if cmd.Stderr != nil {
execCmd.Stderr = cmd.Stderr
}
execCmd.Dir = cmd.WorkingDir
var env []string
if !cmd.UseIsolatedEnv {
env = os.Environ()
}
if cmd.UseIsolatedEnv && runtime.GOOS == "windows" {
panic("UseIsolatedEnv is not supported on Windows")
}
execCmd.Env = mergeEnv(env, cmd.Env)
return execCmd
}