This repository has been archived by the owner on Sep 18, 2022. It is now read-only.
/
golist.go
388 lines (341 loc) · 10.1 KB
/
golist.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
package golist
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/hashicorp/go-multierror"
)
// IndentSize is the number of spaces to indent each line
// per task-depth level.
const IndentSize = 2
// Default List print delay
var DefaultListDelay = time.Millisecond * 100
var (
// ErrListNotRunning is returned when certain functions (like `Println`)
// are called that require the `List` to be running in order to work.
ErrListNotRunning = errors.New("list not running")
// ErrNoWriter is returned when the list is created without an `io.Writer`
ErrNoWriter = errors.New("no writer specified")
// ErrNilAction is returned when no action is set for a task
ErrNilAction = errors.New("nil action")
)
// TaskStatus represents the current status of a task
type TaskStatus int
const (
TaskNotStarted TaskStatus = iota // TaskNotStarted is the status for a task that hasn't started running yet
TaskInProgress // TaskInProgress is the status for a task that is currently running
TaskCompleted // TaskCompleted is the status for a task that has completed successfully
TaskFailed // TaskFailed is the status for a task that returned a non-`nil` error
TaskSkipped // TaskSkipped is the status for a task that was skipped (either manually or from a previous task's error)
)
// Format a TaskStatus as a string
func (s TaskStatus) String() string {
switch s {
case TaskNotStarted:
return "Not Started"
case TaskInProgress:
return "In Progress"
case TaskCompleted:
return "Completed"
case TaskFailed:
return "Failed"
case TaskSkipped:
return "Skipped"
default:
return "Unknown"
}
}
// List is the top-level list object that
// represents a group of tasks to be run.
//
// Generally, you'll want to use the `NewList`
// to create a new list with some sensible defaults.
//
// Otherwise, when creating a new list, you'll at
// least need to set `Writer`, `Delay`, and `StatusIndicator`.
type List struct {
Writer io.Writer // Writer to use for printing output
Delay time.Duration // Delay between prints
StatusIndicator StatusIndicators // Map of statuses to status indicators
Tasks []TaskRunner // List of tasks to run
FailOnError bool // If true, the task execution stops on the first error. Note: this will be ignored if Concurrent is true.
MaxLineLength int // Maximum line length for printing (0 = no limit)
ClearOnComplete bool // If true, the list will clear the list after it finishes running
Concurrent bool // Should the tasks be run concurrently? Note: If true, ignores the FailOnError flag
running bool // Is the list running?
cancel context.CancelFunc // A context cancel function for stopping the list run
printQ chan string // A channel for printing to the terminal while displaying the list
}
// NewList creates a new task list with some sensible defaults.
// It writes to stdout and and has a delay of 100ms between prints.
func NewList() *List {
return &List{
Writer: os.Stdout,
Delay: DefaultListDelay,
StatusIndicator: CreateDefaultStatusIndicator(),
}
}
// NewList creates a new task list that writes to the
// provided io.Writer. Mostly used for testing.
func NewListWithWriter(w io.Writer) *List {
return &List{
Writer: w,
Delay: DefaultListDelay,
StatusIndicator: CreateDefaultStatusIndicator(),
}
}
// AddTask adds a TaskRunner to the top-level List
// and returns a pointer to itself.
func (l *List) AddTask(t TaskRunner) *List {
if l.Tasks == nil {
l.Tasks = make([]TaskRunner, 0)
}
l.Tasks = append(l.Tasks, t)
return l
}
// Start begins displaying the list statuses
// from a background goroutine.
//
// Note: If the list is created without a writer,
// it will be set to `os.Stdout`.
func (l *List) Start() {
if l.Writer == nil {
l.Writer = os.Stdout
}
// Check if it's already displaying
if l.running {
return
}
// Create a cancelable context
ctx, cancel := context.WithCancel(context.Background())
l.cancel = cancel
// Create the channel for printing
l.printQ = make(chan string)
// Start the display loop
go func() {
for {
select {
case <-ctx.Done(): // Check if the print loop should stop
return
case s := <-l.printQ: // Check if there's a message to print
fmt.Fprintln(l.Writer, s)
default: // Otherwise, print the list
ts := l.getTaskStates()
l.print(ts)
l.StatusIndicator.Next()
time.Sleep(time.Millisecond * 100)
l.clear(ts)
}
}
}()
// Set the running flag
l.running = true
}
// runSync runs the TaskRunners in this TaskGroup synchronously
func (l *List) runSync(c TaskContext) error {
var skipRemaining bool
for _, t := range l.Tasks {
if skipRemaining {
t.SetStatus(TaskSkipped)
continue
}
err := t.Run(c)
if err != nil && l.FailOnError {
skipRemaining = true
}
}
return l.GetError()
}
// runAsync runs the TaskRunners in this TaskGroup concurrently
// and blocks until they are all done.
func (l *List) runAsync(c TaskContext) error {
var wg sync.WaitGroup
for _, t := range l.Tasks {
wg.Add(1)
go func(t TaskRunner, c TaskContext) {
defer wg.Done()
t.Run(c)
}(t, c)
}
wg.Wait()
time.Sleep(l.Delay)
return l.GetError()
}
// Run starts running the tasks in the `List`
// and if `FailOnError` is set to true, returns
// an error if any of the tasks fail.
func (l *List) Run() error {
// Starts the list if it hasn't already started
l.Start()
// Create a "base context"
rootTaskCtx := &taskContext{
setMessage: func(m string) {},
println: func(a ...interface{}) error {
return l.Println(a...)
},
printfln: func(f string, a ...interface{}) error {
return l.Printfln(f, a...)
},
}
// If running concurrently...
var err error
if l.Concurrent {
err = l.runAsync(rootTaskCtx)
} else {
// Otherwise, run synchronously
err = l.runSync(rootTaskCtx)
}
// Return the error
return err
}
// Stop stops displaying the task list statuses and
// cancels the background goroutine.
//
// Stop also clears and prints one final time
// before finishing.
func (l *List) Stop() {
// Check if it's already NOT displaying
if !l.running {
return
}
// Send the cancel signal
if l.cancel != nil {
l.cancel()
}
if l.printQ != nil {
close(l.printQ)
}
// Clear and print one final time (NOTE: should this be an option?)
ts := l.getTaskStates()
l.clear(ts)
if !l.ClearOnComplete {
l.print(ts)
}
l.running = false
l.cancel = nil
l.printQ = nil
}
// RunAndWait starts to display the task list statuses,
// runs the tasks, and waits for the tasks to complete
// before returning.
//
// RunAndWait is a convenience function that combines
// `Start`, `Run`, and `Stop`.
func (l *List) RunAndWait() error {
l.Start()
err := l.Run()
if err != nil {
return err
}
l.Stop()
return nil
}
// getTaskStates returns a slice of TaskStates
// for all child tasks
func (l *List) getTaskStates() []*TaskState {
var messages []*TaskState
for _, t := range l.Tasks {
msgs := t.GetTaskStates()
messages = append(messages, msgs...)
}
return messages
}
// truncateMessage will truncate the message to if it's too long
// based on the size parameter.
//
// If the message is truncated, all trailing spaces will be removed
// and an ellipsis ("…") is added to the end. An extra character
// will be removed to fit the elipsis, if necessary. If the size
// is 0, an ellipsis character is still returned.
func (l *List) truncateMessage(m string, size int) string {
rm := []rune(m)
if len(rm) <= size { // No truncation needed
return m
}
if size <= 1 { // Truncate everything
return "…"
}
// Remove an extra character to fit the ellipsis
tsize := size - 1
return strings.TrimSuffix(string(rm[0:tsize]), " ") + "…"
}
// formatMessage formats a message row for displaying.
// The format used is: [depth] [status] [message]
// and it's length is (optionally) limited by the
// MaxLineLength parameter.
func (l *List) formatMessage(m *TaskState) string {
n := m.Depth * IndentSize
d := strings.Repeat(" ", n)
i := l.StatusIndicator.Get(m.Status)
// If no no truncate text, just return the formatted
// status message
if l.MaxLineLength == 0 {
return fmt.Sprintf("%s%s %s", d, i, m.Message)
}
// Otherwise, truncate the result
size := l.MaxLineLength - (n + 1)
return fmt.Sprintf("%s%s %s", d, i, l.truncateMessage(m.Message, size))
}
// print prints the current task states
func (l *List) print(states []*TaskState) {
for _, m := range states {
fmt.Fprintln(l.Writer, l.formatMessage(m))
}
}
// print prints the current task states
func (l *List) clear(states []*TaskState) {
n := len(states)
s := "\033[1A" // Move up a line
s += "\033[K" // Clear the line
s += "\r" // Move back to the beginning of the line
for i := 0; i < n; i++ {
fmt.Fprint(l.Writer, s)
}
}
// Println prints information to the List's Writer (which is
// most likely stdout), like `fmt.Println`.
//
// Internally, it passes information to a channel that will
// be read by the display goroutine and printed safely in
// between updates to the task-list.
//
// Note: If Println is called while the list is not running,
// it will return the error ErrListNotRunning.
func (l *List) Println(a ...interface{}) error {
if l.printQ == nil {
return ErrNoWriter
}
s := fmt.Sprint(a...)
l.printQ <- s
return nil
}
// Printfln prints a formatted string to the list's writer
// (which is usually stdout) before reprinting the list.
//
// Printfln is like Printf but adds a newline character at
// the end of the string. It requires that there be a newline
// character so that the list can be reprinted properly.
//
// Note: If Printfln is called while the list is not running,
// it will return the error ErrListNotRunning.
func (l *List) Printfln(f string, d ...interface{}) error {
if l.printQ == nil {
return ErrNoWriter
}
s := fmt.Sprintf(f, d...)
l.printQ <- s
return nil
}
// GetError returns the errors from the child tasks
func (l *List) GetError() error {
var err *multierror.Error
for _, t := range l.Tasks {
err = multierror.Append(err, t.GetError())
}
return err.ErrorOrNil()
}