-
Notifications
You must be signed in to change notification settings - Fork 7
/
hubble.go
306 lines (269 loc) · 6.88 KB
/
hubble.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package hubble
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/zieckey/goini"
)
func Run(argv []string, rcLocations []string) {
conf := &Config{IncludeLocalEnv: true}
if os.Getenv("HUBBLE_DEBUG") != "" {
fmt.Printf("Debug on\n")
conf.Debug = true
}
// Read all the rc files
rc, err := parseRCFiles(conf, rcLocations)
checkErr(err, "while parsing configs")
// Figure out which env the user has chosen
cmdArgs, choice, err := evalArgs(argv, conf, rc)
checkErr(err, "")
if conf.Debug {
fmt.Printf("Config:\n")
fmt.Printf(" Env: %s\n", choice)
fmt.Printf(" IncludeLocalEnv: %t\n", conf.IncludeLocalEnv)
}
// Run the command in each environment
environments := getEnvironments(choice, rc)
var cmds []*exec.Cmd
// Execute a command for each environment defined
for _, env := range environments {
// Get the command to execute
cmd, err := getCmd(argv, rc, env)
checkErr(err, "")
if conf.Debug {
fmt.Printf("===========================\n")
fmt.Printf("Cmd: \n %s\n", cmd)
fmt.Printf("Environment:\n")
fmt.Printf(" %s\n", strings.Join(env.ToSlice(), "\n "))
}
// Include our current environment
if conf.IncludeLocalEnv {
for _, pair := range os.Environ() {
parts := strings.SplitN(pair, "=", 2)
if _, ok := env[parts[0]]; !ok {
env[parts[0]] = parts[1]
}
}
}
cmds = append(cmds, &exec.Cmd{
Path: cmd,
Args: append([]string{cmd}, cmdArgs...),
Stdout: os.Stdout,
Stderr: os.Stderr,
Env: env.ToSlice(),
})
}
// If only one command, then return the appropriate return code
if len(cmds) == 1 {
err := cmds[0].Run()
if err != nil {
e, ok := err.(*exec.ExitError)
if !ok {
checkErr(err, "")
}
os.Exit(e.ProcessState.ExitCode())
}
return
}
var hadErr bool
for _, cmd := range cmds {
if err := cmd.Run(); err != nil {
fmt.Print(err)
hadErr = true
}
}
if hadErr {
os.Exit(1)
}
}
func expand(path string) string {
usr, _ := user.Current()
dir := usr.HomeDir
if path == "~" {
// In case of "~", which won't be caught by the "else if"
path = dir
} else if strings.HasPrefix(path, "~/") {
// Use strings.HasPrefix so we don't match paths like
// "/something/~/something/"
path = filepath.Join(dir, path[2:])
}
return path
}
// Finds all given and default configs loading each in order
func parseRCFiles(conf *Config, p []string) (*goini.INI, error) {
paths := []string{expand("~/.hubblerc"), ".hubblerc"}
paths = append(paths, p...)
result := goini.New()
for _, file := range paths {
if conf.Debug {
fmt.Printf("Read: %s\n", file)
}
contents, err := ioutil.ReadFile(file)
if err != nil {
continue
}
ini := goini.New()
ini.SetParseSection(true)
ini.SetSkipCommits(true)
if err := ini.Parse(contents, goini.DefaultLineSeparator, goini.DefaultKeyValueSeparator); err != nil {
return nil, errors.Wrapf(err, "while parsing '%s'", file)
}
result.Merge(ini, true)
}
if len(result.GetAll()) == 0 {
return nil, fmt.Errorf("no configs read; attempted [%s]", strings.Join(paths, ", "))
}
return result, nil
}
func checkErr(err error, msg string) {
if err != nil {
if msg != "" {
fmt.Fprintf(os.Stderr, "-- %s: %s\n", msg, err)
} else {
fmt.Fprintf(os.Stderr, "-- %s\n", err)
}
os.Exit(1)
}
}
func getCmd(argv []string, conf *goini.INI, env envMap) (string, error) {
// If our invocation name is not 'hubble'
if !strings.HasSuffix(argv[0], "hubble") {
baseName := path.Base(argv[0])
if result, ok := conf.SectionGet("hubble-commands", baseName); ok {
return result, nil
}
}
// TODO: If hubbleArgs has an execute option defined
// Else, use the cmd if defined
cmd, ok := env["cmd"]
if !ok {
return "", errors.New("please specify a 'cmd' somewhere in your config")
}
return exec.LookPath(cmd)
}
type envMap map[string]string
func (e envMap) ToSlice() []string {
result := make([]string, len(e))
var i = 0
for k, v := range e {
result[i] = fmt.Sprintf("%s=%s", k, v)
i++
}
return result
}
func getEnvironments(choice string, conf *goini.INI) []envMap {
root := make(map[string]string)
sections := []string{choice}
// Source values that are not in a section
kv, ok := conf.GetKvmap(goini.DefaultSection)
if ok {
root = copyEnv(kv)
}
// Support the original hubble default section
kv, ok = conf.GetKvmap("hubble")
if ok {
for k, v := range kv {
root[k] = v
}
}
// Populate the environment variables from the chosen section
kv, _ = conf.GetKvmap(choice)
for k, v := range kv {
if k == "meta" {
sections = toSlice(v, nil)
}
root[k] = v
}
var result []envMap
for _, section := range sections {
// Copy the values from the inherited env
env := copyEnv(root)
// Add the name of the section
env["section"] = section
// Add the chosen section
kv, _ := conf.GetKvmap(choice)
for k, v := range kv {
env[k] = v
}
// TODO: Expand opt.%s
// TODO: Expand ${variables}
// TODO: run opt-cmd and opt-env
result = append(result, env)
}
return result
}
func copyEnv(src map[string]string) map[string]string {
dst := make(map[string]string, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
type Config struct {
IncludeLocalEnv bool
Debug bool
}
func evalArgs(argv []string, conf *Config, rc *goini.INI) (cmdArgs []string, env string, err error) {
// TODO: Get this from thrawn01/cli
conf = &Config{IncludeLocalEnv: true}
env, ok := rc.Get("default-env")
if !ok {
// If no default-env defined, env should be the first arg
if len(argv) == 1 {
return nil, "", errors.New("no 'default-env' defined and no environment provided vi cli args")
}
env = argv[1]
if len(argv) > 2 {
cmdArgs = argv[2:]
}
}
_, ok = rc.GetKvmap(env)
if !ok {
var sections []string
for k := range rc.GetAll() {
if k == goini.DefaultSection {
continue
}
sections = append(sections, k)
}
return nil, "", fmt.Errorf("env '%s' not defined in config; environments configured: %s",
env, strings.Join(sections, ","))
}
// TODO: Use thrawn/cli to parse what args we know about, and leave the rest for the command
return cmdArgs, env, nil
}
// Given a python like array, return a slice of string items.
// Return the entire string as the first item if no comma is found.
// Ignores commas inside a quote `["1,234", "20,2020", "1,1"]`
func toSlice(value string, modifiers ...func(s string) string) []string {
value = strings.Trim(value, "[]")
lastQuote := rune(0)
result := strings.FieldsFunc(value, func(c rune) bool {
switch {
case c == lastQuote:
lastQuote = rune(0)
return false
case lastQuote != rune(0):
return false
case unicode.In(c, unicode.Quotation_Mark):
lastQuote = c
return false
default:
return c == ','
}
})
// Apply the modifiers
for _, modifier := range modifiers {
for idx, item := range result {
result[idx] = modifier(item)
}
}
return result
}