-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
522 lines (447 loc) · 9.92 KB
/
main.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package main
import (
"fmt"
"github.com/troykinsella/bacon/executor"
"github.com/troykinsella/bacon/expander"
"github.com/troykinsella/bacon/watcher"
"github.com/urfave/cli"
"os"
"github.com/troykinsella/bacon/baconfile"
"errors"
"io/ioutil"
"github.com/troykinsella/bacon/util"
"strings"
"bufio"
"path/filepath"
)
const (
AppName = "bacon"
baconFile = "b"
baconFileLong = baconFile + ", baconfile"
command = "c"
commandLong = command + ", cmd"
passCommand = "p"
passCommandLong = passCommand + ", pass"
failCommand = "f"
failCommandLong = failCommand + ", fail"
watch = "w"
watchLong = watch + ", watch"
watchExclude = "e"
watchExcludeLong = watchExclude + ", exclude"
showOutput = "o"
showOutputLong = showOutput + ", show-output"
noNotify = "no-notify"
shell = "shell"
defaultTarget = "default"
)
var (
AppVersion = "0.0.0-dev.0"
)
func newExecutor(c *cli.Context) (*executor.E, error) {
cmds := c.StringSlice(command)
if cmds == nil || len(cmds) == 0 {
return nil, cli.NewExitError(command+" option required", 1)
}
passCmds := c.StringSlice(passCommand)
failCmds := c.StringSlice(failCommand)
sh := c.String(shell)
showOut := c.Bool(showOutput)
e := executor.New(
cmds,
passCmds,
failCmds,
sh,
"",
showOut,
)
return e, nil
}
func newBacon(c *cli.Context) (*Bacon, error) {
exp := expander.New(
"",
c.StringSlice(watch),
c.StringSlice(watchExclude),
)
w, err := watcher.New(exp)
if err != nil {
return nil, err
}
exec, err := newExecutor(c)
if err != nil {
return nil, err
}
showOut := c.Bool(showOutput)
noNotify := c.Bool(noNotify)
b := NewBacon(
w,
exec,
showOut,
!noNotify,
)
return b, nil
}
func newListCommand() *cli.Command {
return &cli.Command{
Name: "list",
Usage: "Print effective files to watch given inclusion and exclusion globs and exit.",
Action: func(c *cli.Context) error {
includes := c.StringSlice(watch)
excludes := c.StringSlice(watchExclude)
e := expander.New("", includes, excludes)
list, err := e.List()
if err != nil {
return err
}
for _, f := range list {
fmt.Println(f)
}
return nil
},
Flags: newWatchFlags(),
}
}
func readString(in *bufio.Scanner, msg string, def string) string {
if def == "" {
fmt.Printf("%s: ", msg)
} else {
fmt.Printf("%s [%s]: ", msg, def)
}
in.Scan()
t := in.Text()
if t == "" {
t = def
}
return t
}
func readStringSlice(in *bufio.Scanner, msg string, def string, requireOne bool) []string {
result := []string{}
i := 0
for {
d := def
if i > 0 {
d = ""
}
s := readString(in, msg, d)
if s == "" && requireOne {
fmt.Println("At least one value is required")
continue
}
if s == "" {
break
}
result = append(result, s)
if !readYesNo(in, "↪ Another list entry?", false) {
break
}
i = i + 1
}
return result
}
func readYesNo(in *bufio.Scanner, msg string, def bool) bool {
var defStr string
if def {
defStr = "Yn"
} else {
defStr = "yN"
}
fmt.Printf("%s [%s]: ", msg, defStr)
in.Scan()
t := in.Text()
if t == "" {
return def
}
return t == "y" || t == "Y"
}
func newInitCommand() *cli.Command {
return &cli.Command{
Name: "init",
Usage: "Create a Baconfile by asking you questions.",
Action: func(c *cli.Context) error {
in := bufio.NewScanner(os.Stdin)
targets := make(map[string]*baconfile.Target)
for {
var tName string
for {
tName = readString(in, "Target name", "default")
if _, exists := targets[tName]; exists {
fmt.Println("Already entered this target name. Enter a different name.")
continue
}
break
}
dir := readString(in, "Working directory for patterns and commands", "")
watch := readStringSlice(in, "Watch file pattern list", "**/*", true)
cmd := readStringSlice(in, "Command list to run when files change", "", true)
pass := readStringSlice(in, "Execute list when the commands pass", "", false)
fail := readStringSlice(in, "Execute list when the commands fail", "", false)
t := &baconfile.Target{
Dir: dir,
Watch: watch,
Command: cmd,
Pass: pass,
Fail: fail,
}
targets[tName] = t
if !readYesNo(in, "Create another target?", false) {
break
}
}
bf := baconfile.B{
Targets: targets,
}
bytes, err := bf.Marshal()
if err != nil {
return err
}
if readYesNo(in, "View Baconfile preview?", false) {
fmt.Print(string(bytes))
}
out := readString(in, "Baconfile path", "Baconfile")
if !filepath.IsAbs(out) {
cwd, err := os.Getwd()
if err != nil {
return err
}
out = filepath.Join(cwd, out)
}
if readYesNo(in, "Write Baconfile to " + out + "?", true) {
err := ioutil.WriteFile(out, bytes, 0644)
if err != nil {
return err
}
}
return nil
},
}
}
func newCommandCommand() *cli.Command {
return &cli.Command{
Name: "command",
Usage: "Execute commands once and exit. Useful for testing a command chain.",
Action: func(c *cli.Context) error {
e, err := newExecutor(c)
if err != nil {
return err
}
r := e.RunCommands("", nil)
if !r.Passing {
return cli.NewExitError("", 1)
}
return nil
},
Flags: newRunFlags(),
}
}
func loadBaconfile(path string, required bool) (*baconfile.B, error) {
exists, err := util.Exists(path)
if err != nil {
return nil, err
}
if !exists {
if required {
return nil, fmt.Errorf("Baconfile not found: %s", path)
}
return nil, nil
}
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
bf, err := baconfile.Unmarshal(bytes)
if err != nil {
return nil, err
}
return bf, nil
}
func findBaconfile(c *cli.Context) (*baconfile.B, error) {
searchOrder := []string{
c.String(baconFile),
"Baconfile",
"Baconfile.yml",
"Baconfile.yaml",
".Baconfile",
".Baconfile.yml",
".Baconfile.yaml",
}
for i, path := range searchOrder {
if path == "" {
continue
}
bf, err := loadBaconfile(path, i == 0)
if err != nil {
return nil, err
}
if bf != nil {
return bf, nil
}
}
return nil, errors.New("Baconfile not found")
}
func newBaconForBaconfile(
c *cli.Context,
bc *baconfile.B,
targetName string,
args []string,
) (*Bacon, error) {
if targetName == "" {
targetName = defaultTarget
}
target := bc.Targets[targetName]
if target == nil {
return nil, fmt.Errorf("Baconfile target not found: %s", targetName)
}
includes := injectArgs(target.Watch, args)
excludes := injectArgs(target.Exclude, args)
exp := expander.New(target.Dir, includes, excludes)
w, err := watcher.New(exp)
if err != nil {
return nil, err
}
showOut := c.GlobalBool(showOutput)
commands := injectArgs(target.Command, args)
passCommands := injectArgs(target.Pass, args)
failCommands := injectArgs(target.Fail, args)
e := executor.New(
commands,
passCommands,
failCommands,
target.Shell,
target.Dir,
showOut,
)
if err != nil {
return nil, err
}
noNotify := c.GlobalBool(noNotify)
b := NewBacon(
w,
e,
showOut,
!noNotify,
)
return b, nil
}
func injectArgs(list []string, args []string) []string {
result := list[:]
for argIndex, arg := range args {
for i, li := range result {
result[i] = injectArg(li, argIndex + 1, arg)
}
}
return result
}
func injectArg(str string, index int, value string) string {
varName := fmt.Sprintf("$%d", index)
return strings.Replace(str, varName, value, -1)
}
func newRunCommand() *cli.Command {
return &cli.Command{
Name: "run",
Usage: "Load configuration from a Baconfile target. The default target name is \"default\".",
ArgsUsage: "[target] [target arguments]",
Action: func(c *cli.Context) error {
bf, err := findBaconfile(c)
if err != nil {
return err
}
var target string
args := c.Args()
if len(args) > 0 {
target = args[0]
args = args[1:]
}
b, err := newBaconForBaconfile(c, bf, target, args)
if err != nil {
return err
}
err = b.Run()
if err != nil {
return err
}
return nil
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: baconFileLong,
Usage: "The `PATH` to the Baconfile to load (default: Baconfile, Baconfile.yml, Baconfile.yaml)",
},
},
}
}
func defCommands(app *cli.App) {
app.Commands = []cli.Command{
*newCommandCommand(),
*newListCommand(),
*newInitCommand(),
*newRunCommand(),
}
}
func newWatchFlags() []cli.Flag {
return []cli.Flag{
cli.StringSliceFlag{
Name: watchLong,
Usage: "Watch the path `GLOB`. Can be repeated. (default: \"**/*\")",
},
cli.StringSliceFlag{
Name: watchExcludeLong,
Usage: "Exclude path `GLOB` matches from being watched. Can be repeated. (default: \"**/.*\")",
},
}
}
func newRunFlags() []cli.Flag {
return []cli.Flag{
cli.StringSliceFlag{
Name: commandLong,
Usage: "Shell `CMD` to execute. Required. Can be repeated.",
},
cli.StringSliceFlag{
Name: passCommandLong,
Usage: "Run the `CMD` when commands pass. Can be repeated.",
},
cli.StringSliceFlag{
Name: failCommandLong,
Usage: "Run the `CMD` when commands fail. Can be repeated.",
},
cli.StringFlag{
Name: shell,
Usage: "The shell with which to interpret commands. (default: \"bash\")",
},
}
}
func newCliApp() *cli.App {
app := cli.NewApp()
app.Name = AppName
app.Version = AppVersion
app.Usage = "Watch files and run commands upon changes"
app.Author = "Troy Kinsella"
app.Action = func(c *cli.Context) error {
b, err := newBacon(c)
if err != nil {
return err
}
err = b.Run()
return err
}
defCommands(app)
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: showOutputLong,
Usage: "Enable command output",
},
cli.BoolFlag{
Name: noNotify,
Usage: "Disable system notifications",
},
}
app.Flags = append(app.Flags, newWatchFlags()...)
app.Flags = append(app.Flags, newRunFlags()...)
return app
}
func main() {
app := newCliApp()
err := app.Run(os.Args)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}