-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-tui.go
More file actions
425 lines (376 loc) · 10.6 KB
/
command-tui.go
File metadata and controls
425 lines (376 loc) · 10.6 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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"github.com/gabriel-vasile/mimetype"
"github.com/mistakenelf/teacup/markdown"
)
type cmdInfoModel struct {
keys cmdInfoKeymap
variableKeys cmdInfoKeymapVariables
help help.Model
markdown markdown.Model
command Command
variables map[string]string
isReadingVariables bool
validationRegex *regexp.Regexp
validationType string
validationData string
textInput textinput.Model
currentVariableInput string
}
type cmdInfoKeymap struct {
Up key.Binding
Down key.Binding
Execute key.Binding
Quit key.Binding
Help key.Binding
}
// ShortHelp returns keybindings to be shown in the mini help view. It's part
// of the key.Map interface.
func (k cmdInfoKeymap) ShortHelp() []key.Binding {
return []key.Binding{k.Execute, k.Help, k.Quit}
}
// FullHelp returns keybindings for the expanded help view. It's part of the
// key.Map interface.
func (k cmdInfoKeymap) FullHelp() [][]key.Binding {
return [][]key.Binding{
{k.Up, k.Down, k.Execute}, // first column
{k.Help, k.Quit}, // second column
}
}
var DefaultKeyMap = cmdInfoKeymap{
Execute: key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "run the command"),
),
Quit: key.NewBinding(
key.WithKeys("q", "ctrl+c", "esc"),
key.WithHelp("q", "quit"),
),
Up: key.NewBinding(
key.WithKeys("up", "k"),
key.WithHelp("↑/k", "move up"),
),
Down: key.NewBinding(
key.WithKeys("down", "j"),
key.WithHelp("↓/j", "move down"),
),
Help: key.NewBinding(
key.WithKeys("?"),
key.WithHelp("?", "toggle help"),
),
}
type cmdInfoKeymapVariables struct {
Execute key.Binding
Quit key.Binding
}
var VariablesKeymap = cmdInfoKeymapVariables{
Execute: key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "save the variable/run command"),
),
Quit: key.NewBinding(
key.WithKeys("ctrl+c", "esc"),
key.WithHelp("ctrl+c", "quit"),
),
}
// ShortHelp returns keybindings to be shown in the mini help view. It's part
// of the key.Map interface.
func (k cmdInfoKeymapVariables) ShortHelp() []key.Binding {
return []key.Binding{k.Execute, k.Quit}
}
// FullHelp returns keybindings for the expanded help view. It's part of the
// key.Map interface.
func (k cmdInfoKeymapVariables) FullHelp() [][]key.Binding {
return [][]key.Binding{
{k.Execute, k.Quit}, // first column
}
}
func newCmdInfoModel(cmd Command) cmdInfoModel {
markdownModel := markdown.New(true, true, lipgloss.AdaptiveColor{Light: "#000000", Dark: "#ffffff"})
markdownModel.FileName = cmd.MarkdownFile
ti := textinput.New()
ti.Placeholder = ""
ti.Focus()
ti.CharLimit = 150
ti.Width = 60
return cmdInfoModel{
markdown: markdownModel,
keys: DefaultKeyMap,
variableKeys: VariablesKeymap,
help: help.New(),
command: cmd,
variables: make(map[string]string),
isReadingVariables: false,
currentVariableInput: "",
textInput: ti,
}
}
// Init intializes the UI.
func (m cmdInfoModel) Init() tea.Cmd {
return nil
}
// Update handles all UI interactions.
func (m cmdInfoModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
switch msg := msg.(type) {
case tea.WindowSizeMsg:
cmds = append(cmds, m.markdown.SetSize(msg.Width, msg.Height))
return m, tea.Batch(cmds...)
case tea.KeyMsg:
if m.isReadingVariables && !key.Matches(msg, m.keys.Execute) && msg.Type != tea.KeyCtrlC {
m.textInput, cmd = m.textInput.Update(msg)
cmds = append(cmds, cmd)
}
if msg.Type == tea.KeyCtrlC {
return m, tea.Quit
}
if !m.isReadingVariables {
switch msg.String() {
case "ctrl+c", "esc", "q":
cmds = append(cmds, tea.Quit)
}
}
switch {
case key.Matches(msg, m.keys.Execute):
if m.isReadingVariables {
setVariable(&m, &cmds)
m = updateVariableMetadata(m)
} else if len(m.command.Variables) > 0 {
// Ask for the variables
m.isReadingVariables = true
m.currentVariableInput = m.command.Variables[0]
m.validationRegex = nil
m.validationType = ""
m.validationData = ""
m = updateVariableMetadata(m)
} else {
// Run the command
generateExecCommand(m.command, m.variables)
cmds = append(cmds, tea.Quit)
}
case key.Matches(msg, m.keys.Help):
m.help.ShowAll = !m.help.ShowAll
case key.Matches(msg, m.keys.Quit) && !m.isReadingVariables:
return m, tea.Quit
}
}
m.markdown, cmd = m.markdown.Update(msg)
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
func updateVariableMetadata(m cmdInfoModel) cmdInfoModel {
commandMetadata := m.command.Metadata
// Get the variable metadata
variableMetadata := commandMetadata[m.currentVariableInput]
// Get the validation
variableValidation := variableMetadata["validation"]
if variableValidation != "" {
// type <data>
// Extract the validation type
reValidationType := regexp.MustCompile("([A-Za-z]+) (.+)")
matches := reValidationType.FindStringSubmatch(variableValidation)
if len(matches) == 3 {
validationType := matches[1]
validationData := matches[2]
switch validationType {
case "file", "regex":
// Check if the regex is valid
regex, err := regexp.Compile("^" + validationData + "$")
if err != nil {
log.Warnf("Invalid regex: %s", validationData)
}
m.validationRegex = regex
}
m.validationType = validationType
m.validationData = validationData
}
}
// Set the placeholder for the textinput if a placeholder exists
variablePlaceholder := variableMetadata["placeholder"]
m.textInput.Placeholder = variablePlaceholder
variableType := variableMetadata["type"]
if variableType == "" {
m.textInput.EchoMode = textinput.EchoNormal
m.textInput.EchoCharacter = ' '
} else if variableType == "password" {
m.textInput.EchoMode = textinput.EchoPassword
m.textInput.EchoCharacter = '•'
}
return m
}
func setVariable(m *cmdInfoModel, cmds *[]tea.Cmd) {
if !m.ValidateInput() {
return
}
// Save the variable
(*m).variables[m.currentVariableInput] = (*m).textInput.Value()
(*m).textInput.SetValue("")
// Check if all variables have been read
var hasMissingVar bool
for _, variable := range (*m).command.Variables {
if _, ok := (*m).variables[variable]; !ok {
// Ask for this variable
(*m).currentVariableInput = variable
hasMissingVar = true
}
}
if !hasMissingVar {
// Run the command
generateExecCommand((*m).command, (*m).variables)
*cmds = append(*cmds, tea.Quit)
}
}
var fileToExecuteOnExit *string
var bashFileContent *string
func generateExecCommand(cmd Command, variables map[string]string) {
// Replace the variables in the content
var newContent string
for _, line := range strings.Split(cmd.Content, "\n") {
for variable, value := range variables {
line = strings.ReplaceAll(line, "{"+variable+"}", value)
line = strings.ReplaceAll(line, "<"+variable+">", value)
}
newContent += line + "\n"
}
bashFileContent = &newContent
// Write the content to a bash file and run that files
tempDir := os.TempDir()
filePath := filepath.Join(tempDir, "cmdwiki-exec-"+cmd.CmdTitle+".sh")
file, err := os.Create(filePath)
if err != nil {
return
}
defer file.Close()
_, err = file.WriteString(newContent)
if err != nil {
return
}
err = file.Close()
if err != nil {
return
}
err = os.Chmod(filePath, 0755)
if err != nil {
return
}
fileToExecuteOnExit = &filePath
}
var mimetypeCache map[string]string
func (m cmdInfoModel) ValidateInput() bool {
input := m.textInput.Value()
var toValidate string
if m.validationType == "regex" {
toValidate = input
} else if m.validationType == "file" {
// Check if we have the mimetype in the cache
if mimetypeCache == nil {
mimetypeCache = make(map[string]string)
}
if mimetypeCache[input] == "" {
// Get the mimetype
mimetype, err := mimetype.DetectFile(input)
if err != nil {
return false
}
mimetypeCache[input] = mimetype.String()
}
toValidate = mimetypeCache[input]
}
if m.validationRegex != nil {
return m.validationRegex.MatchString(toValidate)
}
return true
}
func (m cmdInfoModel) GetValidationError() string {
input := m.textInput.Value()
if m.validationType == "regex" {
return "must match regex: " + m.validationData
} else if m.validationType == "file" {
// Check if we have the mimetype in the cache
if mimetypeCache == nil {
mimetypeCache = make(map[string]string)
}
if mimetypeCache[input] == "" {
// Get the mimetype
mimetype, err := mimetype.DetectFile(input)
if err != nil {
return "file or filetype not found"
}
mimetypeCache[input] = mimetype.String()
}
return "File type must match " + m.validationData + " (was " + mimetypeCache[input] + ")"
}
return "¯\\_(ツ)_/¯"
}
// View returns a string representation of the UI.
func (m cmdInfoModel) View() string {
view := m.markdown.View()
if m.isReadingVariables {
var variableLines string
variableLines += "\n\n"
commandMetadata := m.command.Metadata
// Get the variable metadata
variableMetadata := commandMetadata[m.currentVariableInput]
if variableMetadata == nil {
variableMetadata = make(map[string]string)
}
// Get the description for the variable
variableDescription := variableMetadata["desc"]
if variableDescription != "" {
variableLines += "Description: " + variableDescription + "\n"
}
// Remove 4 lines from the from the bottom
lines := strings.Split(view, "\n")
variableLinesCount := len(strings.Split(variableLines, "\n"))
lines = lines[:len(lines)-4-variableLinesCount]
view = strings.Join(lines, "\n")
view += variableLines
view += "Enter the value for " + m.currentVariableInput + ""
view += m.textInput.View()
// If we have a regex, validate it
if !m.ValidateInput() {
view += " ❌ " + m.GetValidationError()
} else {
view += " ✔️"
}
view += "\n\n"
view += m.help.View(m.variableKeys)
} else {
view += "\n\n"
view += m.help.View(m.keys)
}
return view
}
func showCommmand(cmd Command) {
b := newCmdInfoModel(cmd)
p := tea.NewProgram(b, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
if fileToExecuteOnExit != nil {
// Run the bash script in the terminal
fmt.Println("Running command:")
fmt.Println(*bashFileContent)
fmt.Println("")
execCommand("bash", []string{*fileToExecuteOnExit})
// Remove the file
err := os.Remove(*fileToExecuteOnExit)
if err != nil {
log.Fatal(err)
}
}
}