-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.go
More file actions
77 lines (65 loc) · 1.94 KB
/
exec.go
File metadata and controls
77 lines (65 loc) · 1.94 KB
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
package main
import (
"bytes"
"os"
"os/exec"
"github.com/golang/glog"
)
var (
debug bool
dryrun bool
)
// SetDebug enable true/false debugging output
func SetDebug(enable bool) {
debug = enable
}
// SetDryrun enable true/false dryrun behavior
func SetDryrun(enable bool) {
dryrun = enable
}
// EnvExpansion - check all members of a string slice to see if any are
// environment variables than can be expanded. The function will expand, at
// most, 4 levels of environment variable expansion before stopping.
func EnvExpansion(args []string) []string {
expanded := make([]string, len(args))
copy(expanded, args)
done := false
i := 4 // maximum depth of expansions incase of circular or recursive definition
for !done && i > 0 {
i--
done = true
for index, arg := range expanded {
exp := os.ExpandEnv(arg)
if exp != arg {
done = false
expanded[index] = exp
}
}
}
return expanded
}
// Execute the "command" with the specified arguments and return either;
// on success: the resultant byte array containing stdout, error = nil
// on failure: the resultant byte array containing stderr, error is set
func Execute(command string, arguments []string) ([]byte, error) {
expandedArguments := EnvExpansion(arguments)
cmd := exec.Command(command, expandedArguments...)
stdoutBuf := &bytes.Buffer{}
stderrBuf := &bytes.Buffer{}
cmd.Stdout = stdoutBuf
cmd.Stderr = stderrBuf
if debug || bool(glog.V(4)) {
glog.Infof("run cmd: %s, args: %s", command, arguments)
glog.Infof("run cmd: %s, env ${args}: %s", command, expandedArguments)
}
if dryrun {
return stdoutBuf.Bytes(), nil
}
if err := cmd.Run(); err != nil {
glog.Warningf("cmd: %s, args: %s returned error: %v", command, expandedArguments, err)
glog.V(4).Infof("cmd: %s, stderr: %s", command, string(stderrBuf.Bytes()))
glog.V(4).Infof("cmd: %s, stdout: %v", command, string(stdoutBuf.Bytes()))
return stderrBuf.Bytes(), err
}
return stdoutBuf.Bytes(), nil
}