-
Notifications
You must be signed in to change notification settings - Fork 249
/
template.go
462 lines (420 loc) · 11.8 KB
/
template.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
package mage
// this template uses the "data"
// var only for tests
var mageMainfileTplString = `// +build ignore
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
{{range .Imports}}{{.UniqueName}} "{{.Path}}"
{{end}}
)
func main() {
// Use local types and functions in order to avoid name conflicts with additional magefiles.
type arguments struct {
Verbose bool // print out log statements
List bool // print out a list of targets
Help bool // print out help for a specific target
Timeout time.Duration // set a timeout to running the targets
Args []string // args contain the non-flag command-line arguments
}
parseBool := func(env string) bool {
val := os.Getenv(env)
if val == "" {
return false
}
b, err := strconv.ParseBool(val)
if err != nil {
log.Printf("warning: environment variable %s is not a valid bool value: %v", env, val)
return false
}
return b
}
parseDuration := func(env string) time.Duration {
val := os.Getenv(env)
if val == "" {
return 0
}
d, err := time.ParseDuration(val)
if err != nil {
log.Printf("warning: environment variable %s is not a valid duration value: %v", env, val)
return 0
}
return d
}
args := arguments{}
fs := flag.FlagSet{}
fs.SetOutput(os.Stdout)
// default flag set with ExitOnError and auto generated PrintDefaults should be sufficient
fs.BoolVar(&args.Verbose, "v", parseBool("MAGEFILE_VERBOSE"), "show verbose output when running targets")
fs.BoolVar(&args.List, "l", parseBool("MAGEFILE_LIST"), "list targets for this binary")
fs.BoolVar(&args.Help, "h", parseBool("MAGEFILE_HELP"), "print out help for a specific target")
fs.DurationVar(&args.Timeout, "t", parseDuration("MAGEFILE_TIMEOUT"), "timeout in duration parsable format (e.g. 5m30s)")
fs.Usage = func() {
fmt.Fprintf(os.Stdout, ` + "`" + `
%s [options] [target]
Commands:
-l list targets in this binary
-h show this help
Options:
-h show description of a target
-t <string>
timeout in duration parsable format (e.g. 5m30s)
-v show verbose output when running targets
` + "`" + `[1:], filepath.Base(os.Args[0]))
}
if err := fs.Parse(os.Args[1:]); err != nil {
// flag will have printed out an error already.
return
}
args.Args = fs.Args()
if args.Help && len(args.Args) == 0 {
fs.Usage()
return
}
// color is ANSI color type
type color int
// If you add/change/remove any items in this constant,
// you will need to run "stringer -type=color" in this directory again.
// NOTE: Please keep the list in an alphabetical order.
const (
black color = iota
red
green
yellow
blue
magenta
cyan
white
brightblack
brightred
brightgreen
brightyellow
brightblue
brightmagenta
brightcyan
brightwhite
)
// AnsiColor are ANSI color codes for supported terminal colors.
var ansiColor = map[color]string{
black: "\u001b[30m",
red: "\u001b[31m",
green: "\u001b[32m",
yellow: "\u001b[33m",
blue: "\u001b[34m",
magenta: "\u001b[35m",
cyan: "\u001b[36m",
white: "\u001b[37m",
brightblack: "\u001b[30;1m",
brightred: "\u001b[31;1m",
brightgreen: "\u001b[32;1m",
brightyellow: "\u001b[33;1m",
brightblue: "\u001b[34;1m",
brightmagenta: "\u001b[35;1m",
brightcyan: "\u001b[36;1m",
brightwhite: "\u001b[37;1m",
}
const _color_name = "blackredgreenyellowbluemagentacyanwhitebrightblackbrightredbrightgreenbrightyellowbrightbluebrightmagentabrightcyanbrightwhite"
var _color_index = [...]uint8{0, 5, 8, 13, 19, 23, 30, 34, 39, 50, 59, 70, 82, 92, 105, 115, 126}
colorToLowerString := func (i color) string {
if i < 0 || i >= color(len(_color_index)-1) {
return "color(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _color_name[_color_index[i]:_color_index[i+1]]
}
// ansiColorReset is an ANSI color code to reset the terminal color.
const ansiColorReset = "\033[0m"
// defaultTargetAnsiColor is a default ANSI color for colorizing targets.
// It is set to Cyan as an arbitrary color, because it has a neutral meaning
var defaultTargetAnsiColor = ansiColor[cyan]
getAnsiColor := func(color string) (string, bool) {
colorLower := strings.ToLower(color)
for k, v := range ansiColor {
colorConstLower := colorToLowerString(k)
if colorConstLower == colorLower {
return v, true
}
}
return "", false
}
// Terminals which don't support color:
// TERM=vt100
// TERM=cygwin
// TERM=xterm-mono
var noColorTerms = map[string]bool{
"vt100": false,
"cygwin": false,
"xterm-mono": false,
}
// terminalSupportsColor checks if the current console supports color output
//
// Supported:
// linux, mac, or windows's ConEmu, Cmder, putty, git-bash.exe, pwsh.exe
// Not supported:
// windows cmd.exe, powerShell.exe
terminalSupportsColor := func() bool {
envTerm := os.Getenv("TERM")
if _, ok := noColorTerms[envTerm]; ok {
return false
}
return true
}
// enableColor reports whether the user has requested to enable a color output.
enableColor := func() bool {
b, _ := strconv.ParseBool(os.Getenv("MAGEFILE_ENABLE_COLOR"))
return b
}
// targetColor returns the ANSI color which should be used to colorize targets.
targetColor := func() string {
s, exists := os.LookupEnv("MAGEFILE_TARGET_COLOR")
if exists == true {
if c, ok := getAnsiColor(s); ok == true {
return c
}
}
return defaultTargetAnsiColor
}
// store the color terminal variables, so that the detection isn't repeated for each target
var enableColorValue = enableColor() && terminalSupportsColor()
var targetColorValue = targetColor()
printName := func(str string) string {
if enableColorValue {
return fmt.Sprintf("%s%s%s", targetColorValue, str, ansiColorReset)
} else {
return str
}
}
list := func() error {
{{with .Description}}fmt.Println(` + "`{{.}}\n`" + `)
{{- end}}
{{- $default := .DefaultFunc}}
targets := map[string]string{
{{- range .Funcs}}
"{{lowerFirst .TargetName}}{{if and (eq .Name $default.Name) (eq .Receiver $default.Receiver)}}*{{end}}": {{printf "%q" .Synopsis}},
{{- end}}
{{- range .Imports}}{{$imp := .}}
{{- range .Info.Funcs}}
"{{lowerFirst .TargetName}}{{if and (eq .Name $default.Name) (eq .Receiver $default.Receiver)}}*{{end}}": {{printf "%q" .Synopsis}},
{{- end}}
{{- end}}
}
keys := make([]string, 0, len(targets))
for name := range targets {
keys = append(keys, name)
}
sort.Strings(keys)
fmt.Println("Targets:")
w := tabwriter.NewWriter(os.Stdout, 0, 4, 4, ' ', 0)
for _, name := range keys {
fmt.Fprintf(w, " %v\t%v\n", printName(name), targets[name])
}
err := w.Flush()
{{- if .DefaultFunc.Name}}
if err == nil {
fmt.Println("\n* default target")
}
{{- end}}
return err
}
var ctx context.Context
var ctxCancel func()
getContext := func() (context.Context, func()) {
if ctx != nil {
return ctx, ctxCancel
}
if args.Timeout != 0 {
ctx, ctxCancel = context.WithTimeout(context.Background(), args.Timeout)
} else {
ctx = context.Background()
ctxCancel = func() {}
}
return ctx, ctxCancel
}
runTarget := func(fn func(context.Context) error) interface{} {
var err interface{}
ctx, cancel := getContext()
d := make(chan interface{})
go func() {
defer func() {
err := recover()
d <- err
}()
err := fn(ctx)
d <- err
}()
select {
case <-ctx.Done():
cancel()
e := ctx.Err()
fmt.Printf("ctx err: %v\n", e)
return e
case err = <-d:
cancel()
return err
}
}
// This is necessary in case there aren't any targets, to avoid an unused
// variable error.
_ = runTarget
handleError := func(logger *log.Logger, err interface{}) {
if err != nil {
logger.Printf("Error: %+v\n", err)
type code interface {
ExitStatus() int
}
if c, ok := err.(code); ok {
os.Exit(c.ExitStatus())
}
os.Exit(1)
}
}
_ = handleError
// Set MAGEFILE_VERBOSE so mg.Verbose() reflects the flag value.
if args.Verbose {
os.Setenv("MAGEFILE_VERBOSE", "1")
} else {
os.Setenv("MAGEFILE_VERBOSE", "0")
}
log.SetFlags(0)
if !args.Verbose {
log.SetOutput(ioutil.Discard)
}
logger := log.New(os.Stderr, "", 0)
if args.List {
if err := list(); err != nil {
log.Println(err)
os.Exit(1)
}
return
}
if args.Help {
if len(args.Args) < 1 {
logger.Println("no target specified")
os.Exit(2)
}
switch strings.ToLower(args.Args[0]) {
{{range .Funcs -}}
case "{{lower .TargetName}}":
{{if ne .Comment "" -}}
fmt.Println({{printf "%q" .Comment}})
fmt.Println()
{{end}}
fmt.Print("Usage:\n\n\t{{$.BinaryName}} {{lower .TargetName}}{{range .Args}} <{{.Name}}>{{end}}\n\n")
var aliases []string
{{- $name := .Name -}}
{{- $recv := .Receiver -}}
{{range $alias, $func := $.Aliases}}
{{if and (eq $name $func.Name) (eq $recv $func.Receiver)}}aliases = append(aliases, "{{$alias}}"){{end -}}
{{- end}}
if len(aliases) > 0 {
fmt.Printf("Aliases: %s\n\n", strings.Join(aliases, ", "))
}
return
{{end -}}
{{range .Imports -}}
{{range .Info.Funcs -}}
case "{{lower .TargetName}}":
{{if ne .Comment "" -}}
fmt.Println({{printf "%q" .Comment}})
fmt.Println()
{{end}}
fmt.Print("Usage:\n\n\t{{$.BinaryName}} {{lower .TargetName}}{{range .Args}} <{{.Name}}>{{end}}\n\n")
var aliases []string
{{- $name := .Name -}}
{{- $recv := .Receiver -}}
{{range $alias, $func := $.Aliases}}
{{if and (eq $name $func.Name) (eq $recv $func.Receiver)}}aliases = append(aliases, "{{$alias}}"){{end -}}
{{- end}}
if len(aliases) > 0 {
fmt.Printf("Aliases: %s\n\n", strings.Join(aliases, ", "))
}
return
{{end -}}
{{end -}}
default:
logger.Printf("Unknown target: %q\n", args.Args[0])
os.Exit(2)
}
}
if len(args.Args) < 1 {
{{- if .DefaultFunc.Name}}
ignoreDefault, _ := strconv.ParseBool(os.Getenv("MAGEFILE_IGNOREDEFAULT"))
if ignoreDefault {
if err := list(); err != nil {
logger.Println("Error:", err)
os.Exit(1)
}
return
}
{{.DefaultFunc.ExecCode}}
handleError(logger, ret)
return
{{- else}}
if err := list(); err != nil {
logger.Println("Error:", err)
os.Exit(1)
}
return
{{- end}}
}
for x := 0; x < len(args.Args); {
target := args.Args[x]
x++
// resolve aliases
switch strings.ToLower(target) {
{{range $alias, $func := .Aliases}}
case "{{lower $alias}}":
target = "{{$func.TargetName}}"
{{- end}}
}
switch strings.ToLower(target) {
{{range .Funcs }}
case "{{lower .TargetName}}":
expected := x + {{len .Args}}
if expected > len(args.Args) {
// note that expected and args at this point include the arg for the target itself
// so we subtract 1 here to show the number of args without the target.
logger.Printf("not enough arguments for target \"{{.TargetName}}\", expected %v, got %v\n", expected-1, len(args.Args)-1)
os.Exit(2)
}
if args.Verbose {
logger.Println("Running target:", "{{.TargetName}}")
}
{{.ExecCode}}
handleError(logger, ret)
{{- end}}
{{range .Imports}}
{{$imp := .}}
{{range .Info.Funcs }}
case "{{lower .TargetName}}":
expected := x + {{len .Args}}
if expected > len(args.Args) {
// note that expected and args at this point include the arg for the target itself
// so we subtract 1 here to show the number of args without the target.
logger.Printf("not enough arguments for target \"{{.TargetName}}\", expected %v, got %v\n", expected-1, len(args.Args)-1)
os.Exit(2)
}
if args.Verbose {
logger.Println("Running target:", "{{.TargetName}}")
}
{{.ExecCode}}
handleError(logger, ret)
{{- end}}
{{- end}}
default:
logger.Printf("Unknown target specified: %q\n", target)
os.Exit(2)
}
}
}
`