-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
644 lines (577 loc) · 14 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"strings"
"sync"
"time"
cv "github.com/easeway/go-cliview"
"github.com/easeway/langx.go/errors"
"github.com/ttacon/emoji"
"github.com/codingbrain/clix.go/term"
"github.com/evo-cloud/hmake/docker"
hm "github.com/evo-cloud/hmake/project"
sh "github.com/evo-cloud/hmake/shell"
)
const (
// Release is the major release version
Release = "1.3.1"
// Website is the URL to project website
Website = "https://github.com/evo-cloud/hmake"
timeFmt = "15:04:05.000"
)
// VersionSuffix is pre-release info
var VersionSuffix = "dev"
const (
faceGo int = iota
faceBg
faceOK
faceNA
faceErr
faceAbt
faceAbd
faceStop
faceGood
)
var (
facesNormal = []string{"=>", "<<", ":)", ":]", ":(", "^C", "!!", "--", "OK"}
facesEmoji = []string{
emoji.Emoji(":zap:"),
emoji.Emoji(":relieved:"),
emoji.Emoji(":yum:"),
emoji.Emoji(":expressionless:"),
emoji.Emoji(":disappointed:"),
emoji.Emoji(":x:"),
emoji.Emoji(":bangbang:"),
emoji.Emoji(":recycle:"),
emoji.Emoji(":sunglasses:"),
}
faces = facesNormal
)
type taskState struct {
color string
prefix string
}
type makeCmd struct {
// command line options
Chdir string
File string
Include []string
Properties map[string]interface{} `n:"property"`
Parallel int
RebuildAll bool `n:"rebuild-all"`
RebuildTargets []string `n:"rebuild-target"`
Rebuild bool
Exec bool
ExecWith string `n:"exec-with"`
Skip []string
RcFile bool
JSON bool
Summary bool
Verbose bool
Quiet bool
Banner bool
Color bool
Emoji bool
DebugLog bool `n:"debug-log"`
ShowSummary bool `n:"show-summary"`
ShowTargets bool `n:"targets"`
DryRun bool
Version bool
settings hm.CommonSettings
tasks map[string]*taskState
noNewLine string // name of task printed the last output
lock sync.Mutex
}
var colors = []string{
"blue", "yellow", "green", "magenta", "cyan", "darkgray",
"lightblue", "lightyellow", "lightgreen",
"lightmagenta", "lightcyan", "lightgray",
}
func pad(str string, l int) string {
for i := len(str); i < l; i++ {
str += " "
}
return str
}
// Version returns the full version string
func Version() string {
return Release + VersionSuffix
}
func (c *makeCmd) Execute(args []string) (err error) {
if c.Version {
if c.JSON {
encoded, _ := json.Marshal(Version())
fmt.Println(string(encoded))
} else {
term.Println(Version())
}
return
}
if c.File != "" {
hm.RootFile = c.File
}
if c.Chdir != "" {
if err = os.Chdir(c.Chdir); err != nil {
return
}
}
if c.Banner && (!c.Exec && c.ExecWith == "") {
c.showBanner()
}
var p *hm.Project
if p, err = hm.LocateProject(); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("Unable to find %s", hm.RootFile)
}
return
}
if c.ShowSummary {
err = c.showSummary(p, nil)
return
}
if err = p.Resolve(); err != nil {
return
}
incErrs := &errors.AggregatedError{}
if c.RcFile {
incErrs.Add(p.LoadRcFiles())
}
for _, inc := range c.Include {
_, e := p.Load(inc)
incErrs.Add(e)
}
if err = incErrs.Aggregate(); err != nil {
return
}
if err = p.Finalize(); err != nil {
return
}
if c.Properties != nil {
if err = p.MergeSettingsFlat(c.Properties); err != nil {
return
}
}
names := p.TargetNames()
padLen := 0
for _, name := range names {
if l := len(name); l > padLen {
padLen = l
}
}
if c.ShowTargets {
c.showTargets(p, names, padLen)
return
}
c.tasks = make(map[string]*taskState)
for n, name := range names {
c.tasks[name] = &taskState{
color: colors[n%len(colors)],
prefix: "[" + pad(name+"]", padLen+1) + " ",
}
}
if c.Emoji {
faces = facesEmoji
}
p.GetSettings(&c.settings)
if c.ExecWith != "" {
c.Exec = true
} else if c.Exec {
c.ExecWith = c.settings.ExecTarget
if c.ExecWith == "" {
return fmt.Errorf("exec requires settings.exec-target or use --exec-with")
}
}
// setup verbosity
if !c.Quiet && !c.Exec {
c.Verbose = true
}
if !c.Exec && p.WrapperTarget() == nil && len(args) == 0 {
args = c.settings.DefaultTargets
if len(args) == 0 {
c.showTargets(p, names, padLen)
return fmt.Errorf("no targets selected, please choose at least one from above")
}
}
plan := p.Plan()
plan.Env["HMAKE_VERSION"] = Version()
plan.OnEvent(c.onEvent)
errs := &errors.AggregatedError{}
plan.Rebuild(p.Targets.CompleteNames(c.RebuildTargets, errs)...)
plan.Skip(p.Targets.CompleteNames(c.Skip, errs)...)
var requires []string
if c.Exec {
requires = p.Targets.CompleteNames([]string{c.ExecWith}, errs)
if len(requires) > 0 {
t := p.Targets[requires[0]]
t.Args = args
t.Exec = true
plan.Rebuild(requires[0])
}
} else if t := p.WrapperTarget(); t != nil {
t.Args = args
requires = append(requires, t.Name)
} else if len(args) > 0 && p.IsCommand(args[0]) {
requires = []string{args[0]}
p.Targets[args[0]].Args = args[1:]
} else {
requires = p.Targets.CompleteNames(args, errs)
}
if len(requires) > 1 {
for _, name := range requires {
if t := p.Targets[name]; t != nil && t.Command {
errs.Add(fmt.Errorf("command %s should be the first target", t.Name))
}
}
}
if err = errs.Aggregate(); err != nil {
return
}
if c.Rebuild {
plan.Rebuild(requires...)
}
plan.RebuildAll = c.RebuildAll
plan.MaxConcurrency = c.Parallel
plan.DebugLog = c.DebugLog
plan.DryRun = c.DryRun
if err = plan.Require(requires...); err != nil {
return
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
err = plan.Execute(ch)
if (!c.Exec || c.Verbose) && c.Summary {
c.showSummary(p, plan)
}
if err != nil {
return
}
if c.Verbose || !c.Exec {
term.NewPrinter(term.Std).Styles(term.StyleOK).Println(faces[faceGood])
}
return
}
func (c *makeCmd) showBanner() {
out := term.NewPrinter(term.Std)
out.Styles("lightyellow", term.StyleB).Print("HyperMake").Pop().
Styles(term.StyleHi).Print(" v"+Version()+" ").Pop().
Styles("lightblue", "underline").Println(Website).Pop().
Println()
}
func (c *makeCmd) showTargets(p *hm.Project, names []string, padLen int) {
if c.JSON {
data := make([]map[string]string, 0, len(p.Targets))
for _, name := range names {
t := p.Targets[name]
data = append(data, map[string]string{
"name": t.Name,
"description": t.Desc,
})
}
encoded, _ := json.Marshal(data)
fmt.Println(string(encoded))
} else {
settings := &hm.CommonSettings{}
p.GetSettings(settings)
out := term.NewPrinter(term.Std)
for _, name := range names {
t := p.Targets[name]
found := false
for _, n := range settings.DefaultTargets {
if n == name {
found = true
break
}
}
if found {
out.Styles(term.StyleOK, term.StyleB).Print(" * ").Pop()
} else {
out.Print(" ")
}
out.Styles(term.StyleHi, term.StyleB).
Print(pad(name, padLen+2)).Pop().Println(t.Desc)
}
}
}
func (c *makeCmd) onEvent(event interface{}) {
switch e := event.(type) {
case *hm.EvtTaskStart:
c.dumpEvent("start", e.Task)
c.printTaskState(e.Task, faceGo, "lightblue",
e.Task.StartTime.Format(timeFmt))
case *hm.EvtTaskFinish:
c.dumpEvent("finish", e.Task)
extra := e.Task.FinishTime.Format(timeFmt) +
" [+" + e.Task.Duration().String() + "]"
switch e.Task.Result {
case hm.Started:
c.printTaskState(e.Task, faceBg, term.StyleLo, "")
case hm.Success:
c.printTaskState(e.Task, faceOK, term.StyleOK, extra)
case hm.Skipped:
c.printTaskState(e.Task, faceNA, term.StyleLo, "")
case hm.Failure, hm.Aborted:
c.printTaskState(e.Task, faceErr, term.StyleErr, extra)
if !c.Verbose && (!c.Exec || term.Std.IsTTY() || e.Task.Name() != c.ExecWith) {
c.printFailedTaskOutput(e.Task)
}
}
case *hm.EvtTaskOutput:
c.dumpTaskOutput(e.Task, e.Output)
if c.Verbose {
c.printTaskOutput(e.Task, e.Output)
}
case *hm.EvtTaskAbort:
c.dumpEvent("abort", e.Task)
if e.Abandon {
c.printTaskState(e.Task, faceAbd, term.StyleErr, "")
} else {
c.printTaskState(e.Task, faceAbt, term.StyleWarn, "")
}
case *hm.EvtAbortRequested:
if len(e.Tasks) > 0 {
c.promptAbort(e.Abandon)
}
case *hm.EvtTaskStop:
c.printTaskState(e.Task, faceStop, term.StyleLo, "")
}
}
func (c *makeCmd) printTaskState(task *hm.Task, face int, style, extra string) {
if !c.Verbose && !term.Std.IsTTY() && c.Exec &&
(task.Name() == c.ExecWith ||
(task.Result != hm.Failure && task.Result != hm.Aborted)) {
// suppress state if in exec mode
return
}
c.lock.Lock()
defer c.lock.Unlock()
out := term.NewPrinter(term.Std)
if c.noNewLine != "" {
c.noNewLine = ""
out.Println()
}
out.Styles(term.StyleB, style).Print(faces[face]+" ").Pop().
Styles(term.StyleB, term.StyleHi).Print(task.Name()).Pop()
if extra != "" {
out.Styles(term.StyleLo).Print(" " + extra).Pop()
}
if task.Error != nil {
out.Print(" ").Styles(term.StyleErr).Print(task.Error.Error()).Pop()
}
out.Println()
}
func (c *makeCmd) printTaskOutput(task *hm.Task, p []byte) {
c.lock.Lock()
defer c.lock.Unlock()
s := c.tasks[task.Name()]
out := term.NewPrinter(term.Std).Styles(s.color)
lines := strings.Split(strings.Replace(string(p), "\r\n", "\n", -1), "\n")
for n, line := range lines {
continueLine := n == 0 && c.noNewLine == task.Name()
if n == len(lines)-1 {
if line != "" {
c.noNewLine = task.Name()
} else {
c.noNewLine = ""
break
}
}
if !continueLine {
out.Print(s.prefix)
}
rets := strings.Split(line, "\r")
maxLen := 0
for _, ret := range rets {
if l := len(ret); l > maxLen {
maxLen = l
line = ret
}
}
if continueLine && len(rets) > 1 {
out.Print("\r" + s.prefix)
}
out.Write([]byte(line))
if n < len(lines)-1 {
out.Println()
}
}
}
func (c *makeCmd) printFailedTaskOutput(task *hm.Task) {
f, err := os.Open(sh.LogFile(task))
c.lock.Lock()
defer c.lock.Unlock()
if err != nil {
term.Errorln("Dump output failed: " + err.Error())
return
}
defer f.Close()
out := term.NewPrinter(term.Std).Styles(term.StyleErr)
io.Copy(out, f)
out.Println()
}
func (c *makeCmd) promptAbort(abandon bool) {
out := term.NewPrinter(term.Std)
if abandon {
out.Styles(term.StyleErr).Println("Running targets abandoned!")
} else {
out.Styles(term.StyleWarn).Println("Ctrl-C again to terminate immediately.")
}
}
func (c *makeCmd) dumpEvent(event string, task *hm.Task) {
if !c.JSON {
return
}
e := map[string]interface{}{
"event": event,
"target": task.Name(),
"state": task.State.String(),
}
if task.State >= hm.Running {
e["start-at"] = task.StartTime
}
if task.State >= hm.Abandoned {
e["result"] = task.Result.String()
}
if task.State >= hm.Finished {
e["finish-at"] = task.FinishTime
}
encoded, err := json.Marshal(e)
if err != nil {
return
}
c.lock.Lock()
fmt.Println(string(encoded))
c.lock.Unlock()
}
func (c *makeCmd) dumpTaskOutput(task *hm.Task, out []byte) {
if !c.JSON {
return
}
e := map[string]interface{}{
"event": "output",
"target": task.Name(),
"state": task.State.String(),
"start-at": task.StartTime,
"output": out,
}
encoded, err := json.Marshal(e)
if err != nil {
return
}
c.lock.Lock()
fmt.Println(string(encoded))
c.lock.Unlock()
}
func stylerPrint(text string, styles ...string) string {
var buf bytes.Buffer
term.NewPrinter(&buf).Styles(styles...).Print(text)
return buf.String()
}
func headStyler(class, text string, data interface{}) string {
if strings.HasPrefix(class, "table:head:") {
return stylerPrint(text, term.StyleHi, term.StyleB)
}
return text
}
func resultStyler(class, text string, data interface{}) string {
if strings.HasPrefix(class, "table:row:") {
switch text {
case hm.Success.String():
return stylerPrint(text, term.StyleOK)
case hm.Skipped.String():
return stylerPrint(text, term.StyleLo)
case hm.Failure.String(), hm.Aborted.String():
return stylerPrint(text, term.StyleErr)
default:
return text
}
}
return headStyler(class, text, data)
}
func errorStyler(class, text string, data interface{}) string {
if strings.HasPrefix(class, "table:row:") {
return stylerPrint(text, term.StyleErr)
}
return headStyler(class, text, data)
}
func timeFetcher(col cv.Column, row map[string]interface{}) interface{} {
if timeVal, ok := row[col.Field].(time.Time); ok && !timeVal.IsZero() {
return timeVal.Format(timeFmt)
}
return ""
}
func durationFetcher(col cv.Column, row map[string]interface{}) interface{} {
var startAt, finishAt time.Time
var ok bool
if startAt, ok = row["start-at"].(time.Time); !ok || startAt.IsZero() {
return ""
}
if finishAt, ok = row["finish-at"].(time.Time); !ok || finishAt.IsZero() {
return ""
}
duration := finishAt.Sub(startAt)
if duration == 0 {
return ""
}
return duration.String()
}
func (c *makeCmd) showSummary(p *hm.Project, plan *hm.ExecPlan) (err error) {
var sum hm.ExecSummary
if plan != nil {
sum = plan.Summary
} else {
sum, err = p.Summary()
if err != nil {
return
}
}
if c.JSON {
encoded, _ := json.Marshal(sum)
fmt.Println(string(encoded))
return
}
sumData := make([]map[string]interface{}, len(sum))
for n, s := range sum {
sumData[n] = map[string]interface{}{
"target": s.Target,
"start-at": s.StartAt,
"finish-at": s.FinishAt,
"error": s.Error,
}
if s.Result != hm.Unknown {
sumData[n]["result"] = s.Result.String()
}
}
table := &cv.Table{
Output: cv.Output{
Writer: term.Std,
Styler: headStyler,
},
Border: cv.BorderCompact,
Columns: []cv.Column{
{Title: "Target", Field: "target"},
{Title: "Result", Field: "result", Styler: resultStyler},
{Title: "Duration", Align: cv.AlignRight, Fetcher: durationFetcher},
{Title: "Start", Field: "start-at", Fetcher: timeFetcher},
{Title: "Finish", Field: "finish-at", Fetcher: timeFetcher},
{Title: "Error", Field: "error", Styler: errorStyler},
},
}
w, _, e := term.Size()
if e != nil || w <= 0 {
w = 80
}
table.MaxWidth = w
table.Print(sumData)
return nil
}
func init() {
hm.DefaultExecDriver = docker.ExecDriverName
}
func main() {
cliDef(&makeCmd{}).Parse().Exec()
}