/
task.go
87 lines (76 loc) · 2.11 KB
/
task.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
package cmd
import (
"fmt"
"os"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
"github.com/mattn/go-colorable"
)
type task struct {
name string
spinner spinner.Spinner
finalMSGFormat string
}
// Tasks shows status of registered tasks.
type Tasks struct {
tasks []*task
current int
}
func NewTasks(names []string, opts ...spinner.Option) Tasks {
tasks := make([]*task, 0, len(names))
for i, name := range names {
t := &task{name: name, spinner: *spinner.New(spinner.CharSets[14], 100*time.Millisecond)}
for _, opt := range opts {
opt(&t.spinner)
}
if file, ok := t.spinner.Writer.(*os.File); ok {
t.spinner.Writer = colorable.NewColorable(file)
}
t.spinner.Prefix = " "
t.spinner.Suffix = fmt.Sprintf(" [%d/%d] %s...", i+1, len(names), name)
t.finalMSGFormat = fmt.Sprintf(" [%d/%d] %s (%%s)\n", i+1, len(names), name)
tasks = append(tasks, t)
}
return Tasks{tasks: tasks}
}
// Start starts the first task
func (t *Tasks) Start() {
t.current = 0
t.tasks[t.current].spinner.Start()
}
// Next stops the current task and starts the next task
func (t *Tasks) Next() {
s := color.GreenString("Done")
t.tasks[t.current].spinner.FinalMSG = fmt.Sprintf(t.tasks[t.current].finalMSGFormat, s)
t.tasks[t.current].spinner.Stop()
t.current++
if t.current < len(t.tasks) {
t.tasks[t.current].spinner.Start()
}
}
// Error stops the current task
func (t *Tasks) Error() {
s := color.RedString("Error")
t.tasks[t.current].spinner.FinalMSG = fmt.Sprintf(t.tasks[t.current].finalMSGFormat, s)
t.tasks[t.current].spinner.Stop()
}
func (t *Tasks) Skip() {
s := color.HiBlackString("Skipped")
t.tasks[t.current].spinner.FinalMSG = fmt.Sprintf(t.tasks[t.current].finalMSGFormat, s)
t.tasks[t.current].spinner.Stop()
t.current++
if t.current < len(t.tasks) {
t.tasks[t.current].spinner.Start()
}
}
// Close stops all active tasks
func (t *Tasks) Close() {
for _, task := range t.tasks {
if task.spinner.Active() {
s := color.RedString("Error")
t.tasks[t.current].spinner.FinalMSG = fmt.Sprintf(t.tasks[t.current].finalMSGFormat, s)
task.spinner.Stop()
}
}
}