-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtui.go
More file actions
429 lines (379 loc) · 10.5 KB
/
Copy pathtui.go
File metadata and controls
429 lines (379 loc) · 10.5 KB
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
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// ── ANSI helpers ─────────────────────────────────────────────────────────────
var ansiRE = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]|\x1b][^\x07]*\x07|\r|\x1b[()][AB012]`)
func stripANSI(s string) string { return ansiRE.ReplaceAllString(s, "") }
// fitWidth strips ANSI from s, truncates to w runes, then pads to exactly w.
func fitWidth(s string, w int) string {
s = stripANSI(s)
r := []rune(s)
if len(r) > w {
return string(r[:w])
}
return s + strings.Repeat(" ", w-len(r))
}
// ── Messages ─────────────────────────────────────────────────────────────────
type lineMsg struct {
idx int
line string
}
type exitMsg struct {
idx int
code int
}
type allDoneMsg struct{}
type tickMsg struct{}
// ── Panel ────────────────────────────────────────────────────────────────────
type panel struct {
label string
cmd string
lines []string
mu sync.RWMutex
scroll int
autoScroll bool
status string // "running" | "done" | "failed"
exitCode int
proc *os.Process
}
// signal delivers sig to the panel's process if it's still running. Used to
// stop a panel's subprocess (e.g. `docker compose up`) instead of leaving it
// running in the background after the TUI quits.
func (p *panel) signal(sig os.Signal) {
p.mu.RLock()
proc := p.proc
running := p.status == "running"
p.mu.RUnlock()
if proc != nil && running {
_ = proc.Signal(sig)
}
}
func newPanel(label, cmd string) *panel {
return &panel{label: label, cmd: cmd, autoScroll: true, status: "running"}
}
func (p *panel) push(line string) {
p.mu.Lock()
p.lines = append(p.lines, line)
p.mu.Unlock()
}
func (p *panel) snap() []string {
p.mu.RLock()
defer p.mu.RUnlock()
cp := make([]string, len(p.lines))
copy(cp, p.lines)
return cp
}
// ── Runner ───────────────────────────────────────────────────────────────────
func runPanel(idx int, p *panel, ch chan<- tea.Msg) {
r, w, err := os.Pipe()
if err != nil {
ch <- exitMsg{idx, 1}
return
}
cmd := exec.Command("sh", "-c", p.cmd)
cmd.Stdout = w
cmd.Stderr = w
if err := cmd.Start(); err != nil {
_ = w.Close()
_ = r.Close()
ch <- exitMsg{idx, 1}
return
}
p.mu.Lock()
p.proc = cmd.Process
p.mu.Unlock()
_ = w.Close()
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 512*1024), 512*1024)
for sc.Scan() {
ch <- lineMsg{idx, stripANSI(sc.Text())}
}
_ = r.Close()
code := 0
if err := cmd.Wait(); err != nil {
if ee, ok := err.(*exec.ExitError); ok {
code = ee.ExitCode()
} else {
code = 1
}
}
ch <- exitMsg{idx, code}
}
// ── Styles ───────────────────────────────────────────────────────────────────
var (
hdrActive = lipgloss.NewStyle().
Background(lipgloss.Color("6")).
Foreground(lipgloss.Color("0")).
Bold(true)
hdrIdle = lipgloss.NewStyle().
Background(lipgloss.Color("8")).
Foreground(lipgloss.Color("15"))
barStyle = lipgloss.NewStyle().
Background(lipgloss.Color("0")).
Foreground(lipgloss.Color("7"))
divStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
)
var spinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
func statusFrame(p *panel, tick int) string {
switch p.status {
case "done":
return "✓"
case "failed":
return "✗"
default:
return spinnerFrames[tick%len(spinnerFrames)]
}
}
// ── Model ────────────────────────────────────────────────────────────────────
type model struct {
panels []*panel
focus int
width int
height int
tick int
ch chan tea.Msg
running int
stopping bool
stopPresses int
}
func newModel(panels []*panel) model {
ch := make(chan tea.Msg, 4096)
var wg sync.WaitGroup
for i, p := range panels {
wg.Add(1)
go func(idx int, p *panel) {
defer wg.Done()
runPanel(idx, p, ch)
}(i, p)
}
go func() {
wg.Wait()
ch <- allDoneMsg{}
}()
return model{panels: panels, ch: ch, running: len(panels)}
}
func listenCh(ch chan tea.Msg) tea.Cmd {
return func() tea.Msg { return <-ch }
}
func tickCmd() tea.Cmd {
return tea.Tick(100*time.Millisecond, func(time.Time) tea.Msg { return tickMsg{} })
}
func (m model) Init() tea.Cmd {
return tea.Batch(listenCh(m.ch), tickCmd())
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
n := len(m.panels)
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
case tickMsg:
m.tick++
return m, tickCmd()
case lineMsg:
m.panels[msg.idx].push(msg.line)
return m, listenCh(m.ch)
case exitMsg:
p := m.panels[msg.idx]
p.mu.Lock()
p.exitCode = msg.code
if msg.code == 0 {
p.status = "done"
} else {
p.status = "failed"
}
p.mu.Unlock()
m.running--
if m.stopping && m.running == 0 {
return m, tea.Quit
}
return m, listenCh(m.ch)
case allDoneMsg:
if m.stopping {
return m, tea.Quit
}
return m, nil
case tea.KeyMsg:
p := m.panels[m.focus]
contentH := m.height - 2
switch msg.String() {
case "q", "Q", "ctrl+c":
if m.running == 0 {
return m, tea.Quit
}
m.stopping = true
m.stopPresses++
if m.stopPresses < 3 {
// Forward the interrupt (again) and wait for panels to exit
// on their own. Tools like `docker compose` implement their
// own graceful-then-force handling on a second SIGINT, so we
// keep forwarding rather than killing them ourselves — a
// SIGKILL from us would cut a graceful shutdown off mid-way
// (e.g. containers left running) instead of letting it finish.
for _, panel := range m.panels {
panel.signal(os.Interrupt)
}
return m, nil
}
// Third press: something isn't responding to SIGINT. Force-kill
// as a last resort so the TUI doesn't trap the user forever.
for _, panel := range m.panels {
panel.signal(os.Kill)
}
return m, tea.Quit
case "tab", "right", "l":
m.focus = (m.focus + 1) % n
case "shift+tab", "left", "h":
m.focus = (m.focus - 1 + n) % n
case "up", "k":
p.scroll = imax(0, p.scroll-1)
p.autoScroll = false
case "down", "j":
lines := p.snap()
ms := imax(0, len(lines)-contentH)
if p.scroll < ms {
p.scroll++
} else {
p.autoScroll = true
}
case "pgup", "ctrl+u":
p.scroll = imax(0, p.scroll-contentH)
p.autoScroll = false
case "pgdown", "ctrl+d":
lines := p.snap()
ms := imax(0, len(lines)-contentH)
p.scroll = imin(ms, p.scroll+contentH)
if p.scroll >= ms {
p.autoScroll = true
}
case "g":
p.scroll = 0
p.autoScroll = false
case "G":
p.autoScroll = true
}
}
return m, nil
}
func (m model) renderHeader(p *panel, w int, focused bool) string {
frame := statusFrame(p, m.tick)
text := " " + frame + " " + p.label + " "
r := []rune(text)
switch {
case len(r) > w:
text = string(r[:w])
case len(r) < w:
text += strings.Repeat(" ", w-len(r))
}
if focused {
return hdrActive.Render(text)
}
return hdrIdle.Render(text)
}
func (m model) View() string {
if m.width == 0 {
return "Initializing…"
}
n := len(m.panels)
contentH := m.height - 2 // header row + status bar
// Distribute width: subtract N-1 divider columns, split evenly.
available := m.width - (n - 1)
base := available / n
widths := make([]int, n)
for i := range widths {
widths[i] = base
}
widths[n-1] += available - base*n // remainder goes to last panel
var sb strings.Builder
for row := -1; row < contentH; row++ {
for i, p := range m.panels {
w := widths[i]
var cell string
if row == -1 {
cell = m.renderHeader(p, w, i == m.focus)
} else {
lines := p.snap()
if p.autoScroll {
p.scroll = imax(0, len(lines)-contentH)
}
ms := imax(0, len(lines)-contentH)
if p.scroll > ms {
p.scroll = ms
}
lineIdx := p.scroll + row
if lineIdx >= 0 && lineIdx < len(lines) {
cell = fitWidth(lines[lineIdx], w)
} else {
cell = strings.Repeat(" ", w)
}
}
sb.WriteString(cell)
if i < n-1 {
sb.WriteString(divStyle.Render("│"))
}
}
sb.WriteByte('\n')
}
// Status bar
okCount := 0
for _, p := range m.panels {
if p.status == "done" {
okCount++
}
}
var barText string
switch {
case m.running == 0:
barText = fmt.Sprintf(" Done: %d/%d succeeded [q]uit [tab/←→/h/l]focus [↑↓/PgUp/PgDn/j/k]scroll [g/G]top/end", okCount, n)
case m.stopping:
barText = fmt.Sprintf(" Stopping (%d active)… press %d more time(s) to force quit", m.running, imax(0, 3-m.stopPresses))
default:
barText = fmt.Sprintf(" Running (%d active) [q]uit [tab/←→/h/l]focus [↑↓/PgUp/PgDn/j/k]scroll [g/G]top/end", m.running)
}
sb.WriteString(barStyle.Render(fitWidth(barText, m.width)))
return sb.String()
}
// ── Helpers ──────────────────────────────────────────────────────────────────
func imax(a, b int) int {
if a > b {
return a
}
return b
}
func imin(a, b int) int {
if a < b {
return a
}
return b
}
// runTUI launches the side-by-side TUI for the given panels and blocks until
// the user quits (or all panels finish and the user acknowledges).
// Returns true if all panels succeeded, false if any failed.
func runTUI(panels []*panel) bool {
prog := tea.NewProgram(newModel(panels), tea.WithAltScreen())
if _, err := prog.Run(); err != nil {
fmt.Fprintf(os.Stderr, "tui error: %v\n", err)
return false
}
fmt.Println()
fmt.Println("=== Parallel Summary ===")
ok := true
for _, p := range panels {
if p.status == "done" {
fmt.Printf(" ✓ %s\n", p.label)
} else {
fmt.Printf(" ✗ %s (exit %d)\n", p.label, p.exitCode)
ok = false
}
}
return ok
}