-
Notifications
You must be signed in to change notification settings - Fork 378
/
pager.go
272 lines (233 loc) · 5.87 KB
/
pager.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
package pager
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/armon/circbuf"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/digitalocean/doctl/commands/charm"
"github.com/digitalocean/doctl/commands/charm/template"
"github.com/digitalocean/doctl/commands/charm/text"
)
type WriterStringer interface {
io.Writer
fmt.Stringer
}
type Pager struct {
title string
titleSpinner bool
bufSize int64
buffer WriterStringer
prog *tea.Program
model *pagerModel
exited bool
}
type Option func(*Pager)
func New(opts ...Option) (*Pager, error) {
p := &Pager{
title: "Output",
bufSize: 3 << (10 * 2), // 3MB
}
for _, opt := range opts {
opt(p)
}
var err error
p.buffer, err = circbuf.NewBuffer(p.bufSize)
if err != nil {
return nil, err
}
return p, nil
}
func WithBufferSize(size int64) Option {
return func(p *Pager) {
p.bufSize = size
}
}
func WithTitle(title string) Option {
return func(p *Pager) {
p.title = title
}
}
func WithTitleSpinner(spinner bool) Option {
return func(p *Pager) {
p.titleSpinner = spinner
}
}
func (p *Pager) Write(b []byte) (int, error) {
if p.exited {
return os.Stdout.Write(b)
}
n, err := p.buffer.Write(b)
if p.prog != nil {
p.prog.Send(msgUpdate{})
}
return n, err
}
func (p *Pager) Start(ctx context.Context) error {
p.model = newPagerModel(ctx, p.buffer, p.title, p.titleSpinner)
prog := tea.NewProgram(
p.model,
tea.WithAltScreen(), // use the full size of the terminal in its "alternate screen buffer"
tea.WithMouseCellMotion(), // turn on mouse support so we can track the mouse wheel
)
p.prog = prog
err := prog.Start()
p.exited = true
p.prog = nil
fmt.Fprint(charm.Indent(4), p.buffer.String())
if err != nil {
return err
} else if p.model.userCanceled {
return charm.ErrCanceled
}
return nil
}
type pagerModel struct {
ctx context.Context
cancel context.CancelFunc
start time.Time
title string
buffer WriterStringer
ready bool
viewport viewport.Model
userCanceled bool
spinner *spinner.Model
}
func newPagerModel(ctx context.Context, buffer WriterStringer, title string, titleSpinner bool) *pagerModel {
m := &pagerModel{
buffer: buffer,
title: title,
start: time.Now(),
}
m.ctx, m.cancel = context.WithCancel(ctx)
if titleSpinner {
s := spinner.New(
spinner.WithStyle(text.Muted.Lipgloss()),
spinner.WithSpinner(spinner.Dot),
)
m.spinner = &s
}
return m
}
type msgQuit struct{}
type msgUpdate struct{}
type msgTick struct{}
func (m *pagerModel) Init() tea.Cmd {
cmds := []tea.Cmd{
m.timerTick(),
func() tea.Msg {
<-m.ctx.Done()
return msgQuit{}
},
}
if m.spinner != nil {
cmds = append(cmds, m.spinner.Tick)
}
return tea.Batch(cmds...)
}
func (m *pagerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
switch msg := msg.(type) {
case msgQuit:
return m, tea.Quit
case tea.KeyMsg:
if k := msg.String(); k == "ctrl+c" {
template.Buffered(
m.buffer,
`{{nl}}{{error (print crossmark " got ctrl-c, cancelling. hit ctrl-c again to force exit.")}}{{nl}}`,
nil,
)
m.userCanceled = true
m.cancel()
// we don't need to do anything special to handle the second ctrl-c. the pager exits fairly quickly and once
// that's complete nothing will be intercepting interrupt syscalls and so the second ctrl-c will go directly to
// the go runtime.
return m, nil
}
case tea.WindowSizeMsg:
headerHeight := lipgloss.Height(m.headerView())
footerHeight := lipgloss.Height(m.footerView())
verticalMarginHeight := headerHeight + footerHeight
if !m.ready {
// Since this program is using the full size of the viewport we
// need to wait until we've received the window dimensions before
// we can initialize the viewport. The initial dimensions come in
// quickly, though asynchronously, which is why we wait for them
// here.
m.viewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)
m.viewport.YPosition = headerHeight
m.viewport.SetContent(m.buffer.String())
m.ready = true
} else {
m.viewport.Width = msg.Width
m.viewport.Height = msg.Height - verticalMarginHeight
}
case msgUpdate:
m.viewport.SetContent(m.buffer.String())
m.viewport.GotoBottom()
case msgTick:
if m.ctx.Err() == nil {
cmds = append(cmds, m.timerTick())
}
case spinner.TickMsg:
sp, cmd := m.spinner.Update(msg)
m.spinner = &sp
cmds = append(cmds, cmd)
}
// Handle keyboard and mouse events in the viewport
m.viewport, cmd = m.viewport.Update(msg)
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
func (m *pagerModel) View() string {
if !m.ready {
return "\n loading..."
}
return fmt.Sprintf("%s\n%s%s", m.headerView(), m.viewport.View(), m.footerView())
}
func (m *pagerModel) headerView() string {
// title line
title := m.title
if m.spinner != nil {
title = m.spinner.View() + title
}
title = lipgloss.NewStyle().Padding(1).PaddingBottom(0).Render(title)
// elapsed time + horizontal divider line
elapsed := fmt.Sprintf(
"%s%s%s",
text.Muted.S("───["),
time.Since(m.start).Truncate(time.Second),
text.Muted.S("]"),
)
line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(elapsed)))
line = text.Muted.S(line)
return fmt.Sprintf("%s\n%s%s\n", title, elapsed, line)
}
func (m *pagerModel) footerView() string {
if m.viewport.AtBottom() {
return ""
}
info := "┤ scroll down for new logs "
line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(info)))
return "\n" + text.Highlight.S(line+info)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func (p *pagerModel) timerTick() tea.Cmd {
return tea.Tick(time.Second, func(_ time.Time) tea.Msg {
return msgTick{}
})
}