-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
211 lines (179 loc) · 4.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package make
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/anchore/go-make/color"
)
// Run a command, logging with current stdout / stderr
func Run(cmd ...string) {
cmd = parseCmd(cmd...)
NoErr(Exec(cmd[0], ExecArgs(cmd[1:]...), ExecStd()))
}
func RunWithOptions(cmd string, opts ...ExecOpt) {
cmds := parseCmd(cmd)
opts = append(opts, ExecArgs(cmds[1:]...))
if len(opts) == 0 {
opts = append(opts, ExecStd())
}
NoErr(Exec(cmds[0], opts...))
}
// RunE runs a command, returning stdout, stderr, err
func RunE(cmd ...string) (string, string, error) {
cmd = parseCmd(cmd...)
stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
err := Exec(cmd[0], ExecArgs(cmd[1:]...), func(cmd *exec.Cmd) {
cmd.Stdout = &stdout
cmd.Stderr = &stderr
})
return stdout.String(), stderr.String(), err
}
func parseCmd(cmd ...string) []string {
cmd = append(ShellSplit(cmd[0]), cmd[1:]...)
for i := range cmd {
cmd[i] = Tpl(cmd[i])
}
return cmd
}
// Exec executes the given command, returning stdout and any error information
func Exec(cmd string, opts ...ExecOpt) error {
// add the ToolDir first in the path for easier script writing
lookupPath := os.Getenv("PATH")
defer func() { LogErr(os.Setenv("PATH", lookupPath)) }()
NoErr(os.Setenv("PATH", Tpl(ToolDir)+string(os.PathListSeparator)+lookupPath))
// find exact command, call binny to make sure it's up-to-date
cmd = binnyManagedToolPath(cmd)
// create the command, this will look it up based on path:
c := exec.CommandContext(ctx, cmd)
c.Env = os.Environ()
for k, v := range Globals {
val := ""
switch v := v.(type) {
case func() string:
val = v()
case string:
val = Tpl(v)
default:
continue
}
c.Env = append(c.Env, fmt.Sprintf("%s=%s", k, val))
}
// finally, apply all the options to modify the command
for _, opt := range opts {
opt(c)
}
args := c.Args[1:] // exec.Command sets the cmd to Args[0]
Log("%v %v", displayPath(cmd), strings.Join(args, " "))
// print out c.Env -- GOROOT vs GOBIN
Debug("ENV: %v", c.Env)
// execute
err := c.Start()
if err == nil {
err = c.Wait()
}
if err != nil || (c.ProcessState != nil && c.ProcessState.ExitCode() > 0) {
return &StackTraceError{
Err: fmt.Errorf("error executing: %s %s: %w", cmd, printArgs(args), err),
ExitCode: c.ProcessState.ExitCode(),
}
}
return nil
}
func displayPath(cmd string) string {
wd, err := os.Getwd()
if err != nil {
return auxParent(cmd)
}
absWd, err := filepath.Abs(wd)
if err != nil {
return auxParent(cmd)
}
relPath, err := filepath.Rel(absWd, cmd)
if err != nil {
return auxParent(cmd)
}
return auxParent(relPath)
}
func auxParent(path string) string {
dir, file := filepath.Split(path)
return color.Grey(dir) + file
}
// ExecArgs appends args to the command
func ExecArgs(args ...string) ExecOpt {
return func(cmd *exec.Cmd) {
cmd.Args = append(cmd.Args, args...)
}
}
// ExecStd executes with output mapped to the current process' stdout, stderr, stdin
func ExecStd() ExecOpt {
return func(cmd *exec.Cmd) {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
}
}
// ExecOut sends stdout to the writer, and optionally stderr
func ExecOut(stdout io.Writer, stderr ...io.Writer) ExecOpt {
err := io.Writer(os.Stderr)
if len(stderr) > 1 {
err = stderr[1]
}
return func(cmd *exec.Cmd) {
cmd.Stdout = stdout
cmd.Stderr = err
cmd.Stdin = os.Stdin
}
}
func ExecOutToFile(path string) ExecOpt {
fh, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
NoErr(err)
return func(cmd *exec.Cmd) {
cmd.Stdout = fh
}
}
func ExecErrToFile(path string) ExecOpt {
fh, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
NoErr(err)
return func(cmd *exec.Cmd) {
cmd.Stderr = fh
}
}
// ExecEnv adds an environment variable to the command
func ExecEnv(key, val string) ExecOpt {
return func(cmd *exec.Cmd) {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", key, Tpl(val)))
}
}
// ExecOpts combines all opts into a single one
func ExecOpts(opts ...ExecOpt) ExecOpt {
return func(cmd *exec.Cmd) {
for _, opt := range opts {
opt(cmd)
}
}
}
// ExecOpt is used to alter the command used in Exec calls
type ExecOpt func(*exec.Cmd)
var ctx, cancel = context.WithCancel(context.Background())
// Cancel invokes the cancel call on all active
func Cancel() {
cancel()
}
func printArgs(args []string) string {
for i, arg := range args {
if strings.Contains(arg, " ") {
if strings.Contains(arg, `'`) {
args[i] = `"` + arg + `"`
} else {
args[i] = "'" + arg + "'"
}
}
}
return strings.Join(args, " ")
}