-
Notifications
You must be signed in to change notification settings - Fork 46
/
step.go
132 lines (103 loc) · 1.91 KB
/
step.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package terminal
import (
"context"
"io"
)
const (
TermRows = 10
TermColumns = 100
)
// fancyStepGroup implements StepGroup with live updating and a display
// "window" for live terminal output (when using TermOutput).
type fancyStepGroup struct {
ctx context.Context
cancel func()
display *Display
steps int
done chan struct{}
}
// Start a step in the output
func (f *fancyStepGroup) Add(str string, args ...any) Step {
f.steps++
ent := f.display.NewStatus(0)
ent.StartSpinner()
ent.Update(str, args...)
return &fancyStep{
sg: f,
ent: ent,
}
}
func (f *fancyStepGroup) Wait() {
if f.steps > 0 {
loop:
for {
select {
case <-f.done:
f.steps--
if f.steps <= 0 {
break loop
}
case <-f.ctx.Done():
break loop
}
}
}
f.cancel()
f.display.Close()
}
type fancyStep struct {
sg *fancyStepGroup
ent *DisplayEntry
done bool
status string
term *Term
}
func (f *fancyStep) TermOutput() io.Writer {
if f.term == nil {
t, err := NewTerm(f.sg.ctx, f.ent, TermRows, TermColumns)
if err != nil {
panic(err)
}
f.term = t
}
return f.term
}
func (f *fancyStep) Update(str string, args ...any) {
f.ent.Update(str, args...)
}
func (f *fancyStep) Status(status string) {
f.status = status
f.ent.SetStatus(status)
}
func (f *fancyStep) Done() {
if f.done {
return
}
if f.status == "" {
f.Status(StatusOK)
}
f.signalDone()
}
func (f *fancyStep) Abort() {
if f.done {
return
}
f.Status(StatusError)
f.signalDone()
}
func (f *fancyStep) signalDone() {
f.done = true
f.ent.StopSpinner()
// We don't want to block here because Wait might not yet have been
// called. So instead we just spawn the wait update in a goroutine
// that can also be cancaled by the context.
go func() {
select {
case f.sg.done <- struct{}{}:
case <-f.sg.ctx.Done():
return
}
}()
}