-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
532 lines (466 loc) · 11.4 KB
/
cli.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
package cli
import (
"errors"
"fmt"
"sort"
"strings"
"unicode/utf8"
"github.com/alexrsagen/termbox-go"
)
// ErrNotRunning is returned when a CLI is not running
var ErrNotRunning = errors.New("a CLI is not running")
type pos struct {
x, y int
}
var closed = true
var prefix = "# "
var curPos, termSize pos
var list CommandList
func clearArea(startPos, endPos pos) {
if endPos.y-startPos.y < 0 {
return
}
if endPos.x < 0 {
return
}
for y := startPos.y; y <= endPos.y; y++ {
if y == startPos.y {
if endPos.y-y > 0 {
for x := startPos.x; x <= termSize.x; x++ {
termbox.SetCell(x, y, ' ', termbox.ColorWhite, termbox.ColorDefault)
}
} else {
for x := startPos.x; x <= endPos.x; x++ {
termbox.SetCell(x, y, ' ', termbox.ColorWhite, termbox.ColorDefault)
}
}
} else {
if endPos.y-y > 0 {
for x := 0; x <= termSize.x; x++ {
termbox.SetCell(x, y, ' ', termbox.ColorWhite, termbox.ColorDefault)
}
} else {
for x := 0; x <= endPos.x; x++ {
termbox.SetCell(x, y, ' ', termbox.ColorWhite, termbox.ColorDefault)
}
}
}
}
}
func drawText(cursor int, line string) {
i := 0
// Draw line contents
for _, r := range line {
// Set cursor position
if i == cursor {
termbox.SetCursor(curPos.x, curPos.y)
}
// Set cell contents
switch r {
case '\r':
curPos.x = 0
continue
case '\n':
curPos.x = 0
curPos.y++
continue
default:
termbox.SetCell(curPos.x, curPos.y, r, termbox.ColorWhite, termbox.ColorDefault)
}
// Move cell
curPos.x++
if curPos.x >= termSize.x {
curPos.x = 0
curPos.y++
}
// XXX: handle curPos.y >= termSize.y
// Increment cell counter
i++
}
if i == cursor {
termbox.SetCursor(curPos.x, curPos.y)
}
// Flush contents to terminal
termbox.Flush()
}
func bytePos(runePos int, s string) int {
curRunePos := 0
for curBytePos := range s {
if curRunePos == runePos {
return curBytePos
}
curRunePos++
}
if curRunePos == runePos {
return len(s)
}
// panic because runePos should always be clamped
panic("rune position outside of string range")
}
func parseArgs(args []string) []string {
if args == nil || len(args) == 0 {
return args
}
var newArgs []string
var arg *string
var inQuote, isEscaped bool
for i := range args {
if args[i] == "" {
continue
}
if inQuote || isEscaped {
*arg += " "
isEscaped = false
} else {
newArgs = append(newArgs, "")
arg = &newArgs[len(newArgs)-1]
}
for _, r := range args[i] {
switch r {
case '\\':
if isEscaped {
*arg += "\\"
isEscaped = false
} else {
isEscaped = true
}
case '"':
if isEscaped {
*arg += "\""
isEscaped = false
} else {
inQuote = !inQuote
}
default:
*arg += string(r)
isEscaped = false
}
}
}
return newArgs
}
// Printf outputs the formatted string to the active CLI
func Printf(format string, a ...interface{}) {
if closed {
fmt.Printf(format, a...)
} else {
drawText(-1, fmt.Sprintf(format, a...))
}
}
// Println outputs the operands to the active CLI
func Println(a ...interface{}) {
if closed {
fmt.Println(a...)
} else {
drawText(-1, fmt.Sprintln(a...))
}
}
// Exec attempts to execute a single command, and returns true if the command executed
func Exec(path []string) bool {
items, args, showList := list.resolvePath(path)
if items == nil {
// Do nothing
} else if len(items) == 0 {
// Print command not found message
Println("Command not found")
} else {
if len(items) == 1 && !showList {
// Execute item handler
for name, item := range items {
if item.Handler != nil {
args = parseArgs(args)
if args != nil && len(args) == len(item.Arguments) || len(item.Arguments) == 1 && item.Arguments[0] == "*" {
item.Handler(args)
return true
}
// Print usage message
Printf("Usage: %s", name)
for _, arg := range item.Arguments {
Printf(" <%s>", arg)
}
Printf("\n")
}
break
}
} else {
// Get item keys
var names []string
for name := range items {
names = append(names, name)
}
// Sort item keys alphabetically
sort.Strings(names)
// List sorted items
maxNameLen := 0
for _, name := range names {
if len(name) > maxNameLen {
maxNameLen = len(name)
}
}
maxNameLen += 4
for _, name := range names {
if items[name].Handler != nil {
Printf(strings.Repeat(" ", maxNameLen)+"%s\r%s\n", items[name].Description, name)
}
}
}
}
return false
}
// SetPrefix sets the CLI input prefix string
func SetPrefix(s string) {
prefix = s
}
// SetList sets the CLI command list
func SetList(l CommandList) {
list = l
}
type inputEvent struct {
Type termbox.EventType
Input string
Key termbox.Key
Cursor int
Error error
}
func getInput(startPos pos, cursor int, input string, mask rune) (ev inputEvent) {
if closed {
ev.Type = termbox.EventError
ev.Error = ErrNotRunning
return
}
ev.Input = input
ev.Cursor = cursor
switch tev := termbox.PollEvent(); tev.Type {
case termbox.EventKey:
ev.Type = termbox.EventKey
ev.Key = tev.Key
// Handle keypress
switch tev.Key {
case termbox.KeyTab, termbox.KeyEnd:
// Move cursor pos to end
ev.Cursor = utf8.RuneCountInString(ev.Input)
// Redraw input area
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
case termbox.KeyHome:
// Move cursor pos to start
ev.Cursor = 0
// Redraw input area
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
case termbox.KeyArrowLeft:
// Move cursor pos back
if ev.Cursor > 0 {
ev.Cursor--
// Redraw input area
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
}
case termbox.KeyArrowRight:
// Move cursor pos fwd
if ev.Cursor < utf8.RuneCountInString(ev.Input) {
ev.Cursor++
// Redraw input area
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
}
case termbox.KeyDelete:
cells := utf8.RuneCountInString(ev.Input)
if ev.Input != "" && ev.Cursor < cells {
// Remove character at cursor pos
pos := bytePos(ev.Cursor, ev.Input)
width := bytePos(ev.Cursor+1, ev.Input) - pos
ev.Input = ev.Input[:pos] + ev.Input[pos+width:]
// Redraw input area
clearArea(startPos, curPos)
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
}
case termbox.KeyBackspace:
if ev.Input != "" && ev.Cursor > 0 {
// Remove character before cursor pos
pos := bytePos(ev.Cursor, ev.Input)
width := pos - bytePos(ev.Cursor-1, ev.Input)
ev.Input = ev.Input[:pos-width] + ev.Input[pos:]
// Move cursor pos back
ev.Cursor--
// Redraw input area
clearArea(startPos, curPos)
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
}
case 0, termbox.KeySpace, termbox.KeyCtrl3, termbox.KeyCtrl4, termbox.KeyCtrl5, termbox.KeyCtrl6, termbox.KeyCtrl7, termbox.KeyCtrl8:
// Weird Ctrl+C bug on Windows
if tev.Ch == 0x3 {
ev.Key = termbox.KeyCtrlC
return
}
// Insert character at cursor position in current history entry
pos := bytePos(ev.Cursor, ev.Input)
ev.Input = ev.Input[:pos] + string(tev.Ch) + ev.Input[pos:]
// Move cursor pos fwd
ev.Cursor++
// Redraw input area
curPos = startPos
if mask != 0 {
drawText(ev.Cursor, strings.Repeat(string(mask), utf8.RuneCountInString(ev.Input)))
} else {
drawText(ev.Cursor, ev.Input)
}
}
case termbox.EventResize:
// Store terminal size
termSize.x = tev.Width
termSize.y = tev.Height
case termbox.EventError:
// Return error
ev.Type = termbox.EventError
ev.Error = tev.Err
}
return
}
// Close signals for the CLI to exit on next event
func Close() {
closed = true
}
// Run sets up a new CLI on the process tty
func Run() error {
var log history
var cursor int
// Reset closed state
closed = false
// Initialize terminal
err := termbox.Init()
if err != nil {
return err
}
defer termbox.Close()
// Get initial terminal size
termW, termH := termbox.Size()
termSize.x = termW
termSize.y = termH
// Draw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos := curPos
// Update cursor position
drawText(cursor, "")
for {
switch ev := getInput(startPos, cursor, log.get(), 0); ev.Type {
case termbox.EventKey:
// Clear terminal if new log entry and character was entered
if log.isLast() && log.get() == "" && ev.Key == 0 {
clearArea(curPos, termSize)
termbox.Flush()
}
cursor = ev.Cursor
log.set(ev.Input)
switch ev.Key {
case termbox.KeyCtrlC:
// Clear terminal
termbox.Clear(termbox.ColorWhite, termbox.ColorDefault)
curPos = pos{0, 1}
// Revert current history entry and go to last history entry
if log.isLast() {
log.set("")
} else {
log.revert()
log.last()
}
// Move cursor pos to end
cursor = utf8.RuneCountInString(log.get())
// Redraw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos = curPos
drawText(cursor, log.get())
case termbox.KeyEnter:
// Clear terminal
termbox.Clear(termbox.ColorWhite, termbox.ColorDefault)
curPos = pos{0, 1}
// Attempt to execute command in current history entry
if Exec(strings.Split(strings.Trim(log.get(), " "), " ")) {
if closed {
return nil
}
// If entry is not last, insert new history entry with edited contents and
// restore any edits to original
if !log.isLast() {
log.revertAndAdd()
}
log.new()
cursor = 0
}
// Redraw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos = curPos
drawText(cursor, log.get())
case termbox.KeyTab:
// Clear terminal
termbox.Clear(termbox.ColorWhite, termbox.ColorDefault)
// Autocomplete command in current history entry
curPos.x = 0
curPos.y++
Exec(strings.Split(strings.Trim(log.get()+" ?", " "), " "))
// Redraw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos = curPos
drawText(cursor, log.get())
case termbox.KeyArrowUp:
// If history has a previous entry
if log.prev() {
// Clear terminal
termbox.Clear(termbox.ColorWhite, termbox.ColorDefault)
// Move cursor pos to end
cursor = utf8.RuneCountInString(log.get())
// Redraw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos = curPos
drawText(cursor, log.get())
}
case termbox.KeyArrowDown:
// If history has a next entry
if log.next() {
// Clear terminal
termbox.Clear(termbox.ColorWhite, termbox.ColorDefault)
// Move cursor pos to end
cursor = utf8.RuneCountInString(log.get())
// Redraw input area
curPos = pos{0, 0}
drawText(-1, prefix)
startPos = curPos
drawText(cursor, log.get())
}
}
case termbox.EventError:
return ev.Error
}
}
}