-
Notifications
You must be signed in to change notification settings - Fork 29
/
model_list.go
422 lines (349 loc) · 9.85 KB
/
model_list.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
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
package tui
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/stateful/runme/v3/internal/client/graphql"
"github.com/stateful/runme/v3/internal/client/graphql/query"
"github.com/stateful/runme/v3/internal/gitrepo"
"github.com/stateful/runme/v3/internal/log"
"go.uber.org/zap"
)
var (
appStyle = lipgloss.NewStyle().Margin(1, 2)
listItemStyle = lipgloss.NewStyle().PaddingLeft(0).Bold(true)
editHelpStyle = lipgloss.NewStyle().
PaddingLeft(2).
Foreground(lipgloss.Color("241"))
editInputStyle = lipgloss.NewStyle().
MarginLeft(1).
MarginBottom(2).
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("63")).
Foreground(lipgloss.Color("#87448b"))
editTitleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FAFAFA")).
Background(lipgloss.Color("#5d5dd2")).
MarginLeft(2).
PaddingLeft(1).
PaddingRight(1).
MarginBottom(2)
)
type ListModel struct {
ctx context.Context
client *graphql.Client
log *zap.Logger
repoUser string
description string
suggestions []string
list list.Model
editInput textinput.Model
editHelp help.Model
confirmed bool
loading bool
spinner spinner.Model
selected item
usePrefix bool
err error
}
func NewListModel(ctx context.Context, description string, repoUser string, client *graphql.Client) ListModel {
s := spinner.New()
s.Spinner = spinner.Line
emptyItems := make([]list.Item, 0)
delegate := list.NewDefaultDelegate()
l := list.New(emptyItems, delegate, 0, 0)
l.SetFilteringEnabled(false)
l.SetShowStatusBar(false)
l.SetShowPagination(false)
ti := textinput.New()
ti.Prompt = ""
ti.CharLimit = 250
ti.Width = 50
m := ListModel{
ctx: ctx,
client: client,
log: log.Get().Named("SuggestionsListModel"),
repoUser: repoUser,
description: description,
list: l,
editInput: ti,
editHelp: help.New(),
spinner: s,
confirmed: false,
loading: true,
usePrefix: true,
}
m.list.AdditionalShortHelpKeys = func() []key.Binding {
return m.KeyMap().ShortHelp()
}
m.list.AdditionalFullHelpKeys = func() []key.Binding {
return m.KeyMap().ShortHelp()
}
return m
}
func (m ListModel) Confirmed() bool {
return m.confirmed
}
func (m ListModel) startSearch() tea.Msg {
userBranches, err := gitrepo.GetUsersBranches(m.repoUser)
if err != nil {
// This isn't fatal, we will just defer to the repo branches.
log.Get().Debug("Error preparing users branches", zap.Any("err", err))
}
if len(userBranches) > 100 {
userBranches = userBranches[:100]
}
repoBranches, err := gitrepo.GetRepoBranches()
if err != nil {
// This isn't fatal, worst case we fall back to generic recommendations.
log.Get().Debug("Error preparing repository branches", zap.Any("err", err))
}
if len(repoBranches) > 100 {
repoBranches = repoBranches[:100]
}
input, err := newGetSuggestedBranch(m.description, userBranches, repoBranches)
if err != nil {
return errorMsg{err}
}
log.Get().Debug("prepared GetSuggestedBranch", zap.Any("input", input))
suggestions, err := m.client.GetSuggestedBranch(m.ctx, input)
if err != nil {
log.Get().Debug("Server error when getting suggested branch", zap.Any("input", err))
return errorMsg{err}
}
// Because we are passing this directly into the terminal, let's make sure
// to sanitize it.
suggestions = sanitizeBranchName(suggestions)
log.Get().Debug("Success, updating with suggestions")
return suggestionsMsg{suggestions}
}
func (m ListModel) Init() tea.Cmd {
return tea.Batch(m.startSearch, m.spinner.Tick)
}
type suggestionsMsg struct {
suggestions []string
}
type confirmMsg struct {
response string
}
type errorMsg struct {
Err error
}
func (m ListModel) KeyMap() *KeyMap {
kmap := NewKeyMap()
kmap.Set("enter", key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "select"),
))
kmap.Set("up", m.list.KeyMap.CursorUp)
kmap.Set("down", m.list.KeyMap.CursorDown)
kmap.Set("t", key.NewBinding(
key.WithKeys("t"),
key.WithHelp("t", "toggle prefix"),
))
kmap.Set("e", key.NewBinding(
key.WithKeys("e"),
key.WithHelp("e", "edit branch name"),
))
return kmap
}
func (m ListModel) EditKeyMap() *KeyMap {
editInputKeys := NewKeyMap()
editInputKeys.Set("enter", key.NewBinding(
key.WithKeys("enter", "ctrl+s"),
key.WithHelp("enter/ctrl+s", "save changes"),
))
editInputKeys.Set("esc", key.NewBinding(
key.WithKeys("esc", "esc", "ctrl+c"),
key.WithHelp("esc/ctrl+c", "quit"),
))
return editInputKeys
}
func (m ListModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
h, v := appStyle.GetFrameSize()
m.list.SetSize(msg.Width-h, msg.Height-v)
m.editHelp.Width = msg.Width - h
case spinner.TickMsg:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
case tea.KeyMsg:
if m.editInput.Focused() {
editKmap := m.EditKeyMap()
switch {
case editKmap.Matches(msg, "enter"):
selected := m.list.SelectedItem().(item)
selected.branchName = removeSpecialChars(m.editInput.Value())
m.list.SetItem(m.list.Cursor(), selected)
m.editInput.Blur()
return m, nil
case editKmap.Matches(msg, "esc"):
m.editInput.Blur()
return m, nil
}
m.editInput, cmd = m.editInput.Update(msg)
return m, cmd
}
kmap := m.KeyMap()
switch {
case kmap.Matches(msg, "up"):
m.list.CursorUp()
return m, nil
case kmap.Matches(msg, "down"):
m.list.CursorDown()
return m, nil
case kmap.Matches(msg, "enter"):
if m.loading {
return m, nil
}
selected, ok := m.list.SelectedItem().(item)
return m, func() tea.Msg {
if !ok {
return errorMsg{errors.New("unable to select an item")}
}
m.selected = selected
cwd, err := os.Getwd()
if err != nil {
return errorMsg{err}
}
cmdSlice := []string{"git", "checkout", "-b", m.selected.Suggestion()}
fmt.Printf("Output: %s", cmdSlice)
cmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)
cmd.Dir = cwd
out, err := cmd.CombinedOutput()
if err != nil {
return errorMsg{err}
}
return confirmMsg{string(out)}
}
case kmap.Matches(msg, "t"):
m := m.TogglePrefixes()
return m, nil
case kmap.Matches(msg, "e"):
selected := m.list.SelectedItem().(item)
m.editInput.SetValue(selected.branchName)
m.editInput.Focus()
return m, nil
}
case suggestionsMsg:
m.suggestions = msg.suggestions
for _, s := range m.suggestions {
m.list.InsertItem(0, createListItem(s, true))
}
m.loading = false
return m, nil
case confirmMsg:
m.confirmed = true
fmt.Printf("Output: %s", msg.response)
return m, tea.Quit
case errorMsg:
m.loading = false
m.err = msg.Err
return m, tea.Quit // now fixed https://github.com/charmbracelet/bubbletea/issues/274
}
m.list, cmd = m.list.Update(msg)
return m, cmd
}
func (m ListModel) View() string {
var s string
if m.err != nil {
s := fmt.Sprintf("%s\n", ColorError.Render("Error: "+m.err.Error()))
return s
}
if m.confirmed {
s := fmt.Sprintf("Confirmed: %s", m.selected.branchName)
return s
}
if m.loading {
s := fmt.Sprintf("\n%s loading suggestions...\n", m.spinner.View())
return s
}
if m.editInput.Focused() {
s += editTitleStyle.Render("Edit branch name:") + "\n"
s += editInputStyle.Render(m.editInput.View()) + "\n"
s += editHelpStyle.Render(m.editHelp.View(m.EditKeyMap()))
return appStyle.Render(s)
}
m.list.Title = "How about one of these (generated by AI):"
s += appStyle.Render(m.list.View())
return s
}
type item struct {
branchName string
usePrefix bool
}
func (i item) Title() string { return listItemStyle.Render(i.Suggestion()) }
func (i item) Description() string {
return fmt.Sprintf("git checkout -b '%v'", i.Suggestion())
}
func (i item) FilterValue() string { return i.branchName }
func (i item) Suggestion() string {
if i.usePrefix {
return i.branchName
}
parts := strings.SplitN(i.branchName, "/", 2)
if len(parts) == 2 {
return parts[1]
}
return i.branchName
}
func (m ListModel) TogglePrefixes() ListModel {
m.usePrefix = !m.usePrefix
for idx, i := range m.list.Items() {
item := i.(item)
item.usePrefix = !item.usePrefix
m.list.SetItem(idx, item)
}
return m
}
func createListItem(branchName string, showPrefix bool) item {
return item{branchName: branchName, usePrefix: showPrefix}
}
func newGetSuggestedBranch(description string, userBranches []gitrepo.Branch, repoBranches []gitrepo.Branch) (input query.SuggestedBranchInput, _ error) {
ub := []query.BranchSuggestionInput{}
for _, x := range userBranches {
ub = append(ub, query.BranchSuggestionInput{Branch: x.Name, Description: x.Description})
}
rb := []query.BranchSuggestionInput{}
for _, x := range repoBranches {
rb = append(rb, query.BranchSuggestionInput{Branch: x.Name, Description: x.Description})
}
return query.SuggestedBranchInput{
Description: description,
UserBranches: ub,
RepoBranches: rb,
}, nil
}
func removeSpecialChars(unsanitized string) string {
pattern := regexp.MustCompile(`[^A-Za-z0-9\-_\/]+`)
sanitized := pattern.ReplaceAllString(unsanitized, "")
return sanitized
}
func sanitizeBranchName(unsanitized []string) []string {
// Better safe than sorry - the methodology here is simple - if the string
// contains a character that isn't in our whitelist (alpha, plus dashes)
// then we omit the suggestion.
// Edge case is of course that we are left with an empty list.
isInWhitelist := regexp.MustCompile(`^[A-Za-z0-9-_\/]+$`).MatchString
sanitized := make([]string, 0)
for _, s := range unsanitized {
if isInWhitelist(s) {
sanitized = append(sanitized, s)
}
}
return sanitized
}