-
Notifications
You must be signed in to change notification settings - Fork 64
/
process.go
308 lines (253 loc) · 6.1 KB
/
process.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package paraprogress
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/charmbracelet/bubbles/progress"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/stopwatch"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/reflow/indent"
"kraftkit.sh/log"
"kraftkit.sh/tui"
"kraftkit.sh/utils"
)
var (
lastID int
idMtx sync.Mutex
width = lipgloss.Width
)
func nextID() int {
idMtx.Lock()
defer idMtx.Unlock()
lastID++
return lastID
}
type ProcessStatus uint
const (
StatusPending ProcessStatus = iota
StatusRunning
StatusFailed
StatusSuccess
)
const (
INDENTS = 4
LOGLEN = 5
)
// StatusMsg is sent when the stopwatch should start or stop.
type StatusMsg struct {
ID int
status ProcessStatus
err error
}
// ProgressMsg is sent when an update in the progress percentage occurs.
type ProgressMsg struct {
ID int
progress float64
}
// Process ...
type Process struct {
id int
percent float64
processFunc func(context.Context, func(float64)) error
progress progress.Model
spinner spinner.Model
timer stopwatch.Model
timerWidth int
timerMax int
width int
logs []string
err error
norender bool
ctx context.Context
timeout time.Duration
Name string
NameWidth int
Status ProcessStatus
}
func NewProcess(name string, processFunc func(context.Context, func(float64)) error) *Process {
d := &Process{
id: nextID(),
Name: name,
spinner: spinner.New(),
progress: progress.New(),
timer: stopwatch.NewWithInterval(time.Millisecond * 100),
Status: StatusPending,
NameWidth: len(name),
processFunc: processFunc,
}
d.progress.Full = '•'
d.progress.Empty = ' '
d.progress.EmptyColor = ""
d.progress.FullColor = "245"
d.progress.ShowPercentage = true
d.progress.PercentFormat = " %3.0f%%"
return d
}
func (p *Process) Init() tea.Cmd {
return nil
}
func (p *Process) Start() tea.Cmd {
//nolint:staticcheck
cmds := []tea.Cmd{
p.timer.Init(),
p.spinner.Tick,
func() tea.Msg {
return StatusMsg{
ID: p.id,
status: StatusRunning,
}
},
}
cmds = append(cmds, func() tea.Msg {
p := p // golang closures
if p.norender {
log.G(p.ctx).Info(p.Name)
}
err := p.processFunc(p.ctx, p.onProgress)
p.Status = StatusSuccess
if err != nil {
p.Status = StatusFailed
}
if tprog != nil {
tprog.Send(StatusMsg{
ID: p.id,
status: p.Status,
err: err,
})
}
return nil
})
return tea.Batch(cmds...)
}
// onProgress is called to dynamically inject ProgressMsg into the bubbletea
// runtime
func (p Process) onProgress(progress float64) {
if tprog == nil || progress < 0 {
return
}
tprog.Send(ProgressMsg{
ID: p.id,
progress: progress,
})
}
// Write implements `io.Writer` so we can correctly direct the output from the
// process to an inline fancy logger
func (p *Process) Write(b []byte) (int, error) {
// Remove the last line which is usually appended by a logger
line := strings.TrimSuffix(string(b), "\n")
// Split all lines up so we can individually append them
lines := strings.Split(strings.ReplaceAll(line, "\r\n", "\n"), "\n")
p.logs = append(p.logs, lines...)
return len(b), nil
}
func (p *Process) Close() error {
return nil
}
func (p *Process) Fd() uintptr {
return 0
}
func (d *Process) Update(msg tea.Msg) (*Process, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
d.timer, cmd = d.timer.Update(msg)
cmds = append(cmds, cmd)
switch msg := msg.(type) {
// ProgressMsg is sent when the progress bar wishes
case ProgressMsg:
if msg.ID != d.id {
return d, nil
}
if msg.progress > 1.0 {
msg.progress = 1.0
cmds = append(cmds, d.timer.Stop())
}
d.percent = msg.progress
// TickMsg is sent when the spinner wants to animate itself
case spinner.TickMsg:
if d.timeout != 0 && d.timer.Elapsed() > d.timeout {
d.err = fmt.Errorf("process timedout after %s", d.timeout.String())
d.Status = StatusFailed
cmds = append(cmds, tea.Quit)
}
d.spinner, cmd = d.spinner.Update(msg)
cmds = append(cmds, cmd)
// StatusMsg is sent when the status of the process changes
case StatusMsg:
if msg.ID != d.id {
return d, nil
}
d.Status = msg.status
if d.Status == StatusFailed {
d.err = msg.err
cmds = append(cmds, d.timer.Stop())
} else if d.Status == StatusSuccess {
d.percent = 1.0
cmds = append(cmds, d.timer.Stop())
}
// tea.WindowSizeMsg is sent when the terminal window is resized
case tea.WindowSizeMsg:
d.width = msg.Width
}
return d, tea.Batch(cmds...)
}
func (p Process) View() string {
left := ""
switch p.Status {
case StatusRunning:
left += tui.TextWhiteBgBlue("[" + p.spinner.View() + "]")
case StatusSuccess:
left += tui.TextWhiteBgGreen("[+]")
default:
if p.Status == StatusFailed || p.err != nil {
left += tui.TextWhiteBgRed("<!>")
} else {
left += "[ ]"
}
}
left += " "
leftWidth := width(left)
elapsed := utils.HumanizeDuration(p.timer.Elapsed())
p.timerWidth = width(elapsed)
elapsed = "[" + elapsed + "]"
if p.timerMax-p.timerWidth < 0 {
p.timerMax = p.timerWidth
}
right := " " + tui.TextLightGray(indent.String(elapsed, uint(p.timerMax-p.timerWidth)))
rightWidth := width(right)
middle := lipgloss.NewStyle().
Width(p.NameWidth + 1).
Render(p.Name)
p.progress.Width = p.width - width(middle) - leftWidth - rightWidth
middle += p.progress.ViewAs(p.percent)
s := lipgloss.JoinHorizontal(lipgloss.Top,
left,
middle,
right,
)
// Print the logs for this item
if p.Status != StatusSuccess && p.percent < 1 {
// Newline for the logs
if len(p.logs) > 0 {
s += "\n"
}
truncate := 0
if p.Status != StatusFailed {
loglen := len(p.logs) - LOGLEN
if loglen > 0 {
truncate = loglen
}
}
for _, line := range p.logs[truncate:] {
s += line + "\n"
}
}
return s
}