forked from abiosoft/ishell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ishell.go
675 lines (601 loc) · 14.2 KB
/
ishell.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
// Package ishell implements an interactive shell.
package ishell
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"unicode"
"github.com/chzyer/readline"
"github.com/fatih/color"
"github.com/flynn-archive/go-shlex"
)
const (
defaultPrompt = ">>> "
defaultMultiPrompt = "... "
)
var (
errNoHandler = errors.New("incorrect input, try 'help'")
errNoInterruptHandler = errors.New("no interrupt handler")
)
// Shell is an interactive cli shell.
type Shell struct {
rootCmd *Cmd
generic func(*Context)
interrupt func(*Context, int, string)
interruptCount int
eof func(*Context)
reader *shellReader
writer io.Writer
active bool
activeMutex sync.RWMutex
ignoreCase bool
customCompleter bool
multiChoiceActive bool
haltChan chan struct{}
historyFile string
contextValues map[string]interface{}
autoHelp bool
rawArgs []string
progressBar ProgressBar
Actions
}
// New creates a new shell with default settings. Uses standard output and default prompt ">> ".
func New() *Shell {
return NewWithConfig(&readline.Config{Prompt: defaultPrompt})
}
// NewWithConfig creates a new shell with custom readline config.
func NewWithConfig(conf *readline.Config) *Shell {
rl, err := readline.NewEx(conf)
if err != nil {
log.Println("Shell or operating system not supported.")
log.Fatal(err)
}
shell := &Shell{
rootCmd: &Cmd{},
reader: &shellReader{
scanner: rl,
prompt: rl.Config.Prompt,
multiPrompt: defaultMultiPrompt,
showPrompt: true,
buf: &bytes.Buffer{},
completer: readline.NewPrefixCompleter(),
},
writer: conf.Stdout,
autoHelp: true,
}
shell.Actions = &shellActionsImpl{Shell: shell}
shell.progressBar = newProgressBar(shell)
addDefaultFuncs(shell)
return shell
}
// Start starts the shell but does not wait for it to stop.
func (s *Shell) Start() {
s.prepareRun()
go s.run()
}
// Run starts the shell and waits for it to stop.
func (s *Shell) Run() {
s.prepareRun()
s.run()
}
// Wait waits for the shell to stop.
func (s *Shell) Wait() {
<-s.haltChan
}
func (s *Shell) stop() {
if !s.Active() {
return
}
s.activeMutex.Lock()
s.active = false
s.activeMutex.Unlock()
close(s.haltChan)
}
// Close stops the shell (if required) and closes the shell's input.
// This should be called when done with reading inputs.
// Unlike `Stop`, a closed shell cannot be restarted.
func (s *Shell) Close() {
s.stop()
s.reader.scanner.Close()
}
func (s *Shell) prepareRun() {
if s.Active() {
return
}
if !s.customCompleter {
s.initCompleters()
}
s.activeMutex.Lock()
s.active = true
s.activeMutex.Unlock()
s.haltChan = make(chan struct{})
}
func (s *Shell) run() {
shell:
for s.Active() {
var line []string
var err error
read := make(chan struct{})
go func() {
line, err = s.read()
read <- struct{}{}
}()
select {
case <-read:
break
case <-s.haltChan:
continue shell
}
if err == io.EOF {
if s.eof == nil {
fmt.Println("EOF")
break
}
if err := handleEOF(s); err != nil {
s.Println("Error:", err)
continue
}
} else if err != nil && err != readline.ErrInterrupt {
s.Println("Error:", err)
continue
}
if err == readline.ErrInterrupt {
// interrupt received
err = handleInterrupt(s, line)
} else {
// reset interrupt counter
s.interruptCount = 0
// normal flow
if len(line) == 0 {
// no input line
continue
}
err = handleInput(s, line)
}
if err != nil {
s.Println("Error:", err)
}
}
}
// Active tells if the shell is active. i.e. Start is previously called.
func (s *Shell) Active() bool {
s.activeMutex.RLock()
defer s.activeMutex.RUnlock()
return s.active
}
// Process runs shell using args in a non-interactive mode.
func (s *Shell) Process(args ...string) error {
return handleInput(s, args)
}
func handleInput(s *Shell, line []string) error {
handled, err := s.handleCommand(line)
if handled || err != nil {
return err
}
// Generic handler
if s.generic == nil {
return errNoHandler
}
c := newContext(s, nil, line)
s.generic(c)
return c.err
}
func handleInterrupt(s *Shell, line []string) error {
if s.interrupt == nil {
return errNoInterruptHandler
}
c := newContext(s, nil, line)
s.interruptCount++
s.interrupt(c, s.interruptCount, strings.Join(line, " "))
return c.err
}
func handleEOF(s *Shell) error {
c := newContext(s, nil, nil)
s.eof(c)
return c.err
}
func (s *Shell) handleCommand(str []string) (bool, error) {
if s.ignoreCase {
for i := range str {
str[i] = strings.ToLower(str[i])
}
}
cmd, args := s.rootCmd.FindCmd(str)
if cmd == nil {
return false, nil
}
// trigger help if func is not registered or auto help is true
if cmd.Func == nil || (s.autoHelp && len(args) == 1 && args[0] == "help") {
s.Println(cmd.HelpText())
return true, nil
}
c := newContext(s, cmd, args)
cmd.Func(c)
return true, c.err
}
func (s *Shell) readLine() (line string, err error) {
consumer := make(chan lineString)
defer close(consumer)
go s.reader.readLine(consumer)
ls := <-consumer
return ls.line, ls.err
}
func (s *Shell) read() ([]string, error) {
s.rawArgs = nil
heredoc := false
eof := ""
// heredoc multiline
lines, err := s.readMultiLinesFunc(func(line string) bool {
if !heredoc {
if strings.Contains(line, "<<") {
s := strings.SplitN(line, "<<", 2)
if eof = strings.TrimSpace(s[1]); eof != "" {
heredoc = true
return true
}
}
} else {
return line != eof
}
return strings.HasSuffix(strings.TrimSpace(line), "\\")
})
s.rawArgs = strings.Fields(lines)
if heredoc {
s := strings.SplitN(lines, "<<", 2)
args, err1 := shlex.Split(s[0])
arg := strings.TrimSuffix(strings.SplitN(s[1], "\n", 2)[1], eof)
args = append(args, arg)
if err1 != nil {
return args, err1
}
return args, err
}
lines = strings.Replace(lines, "\\\n", " \n", -1)
args, err1 := shlex.Split(lines)
if err1 != nil {
return args, err1
}
return args, err
}
func (s *Shell) readMultiLinesFunc(f func(string) bool) (string, error) {
var lines bytes.Buffer
currentLine := 0
var err error
for {
if currentLine == 1 {
// from second line, enable next line prompt.
s.reader.setMultiMode(true)
}
var line string
line, err = s.readLine()
fmt.Fprint(&lines, line)
if !f(line) || err != nil {
break
}
fmt.Fprintln(&lines)
currentLine++
}
if currentLine > 0 {
// if more than one line is read
// revert to standard prompt.
s.reader.setMultiMode(false)
}
return lines.String(), err
}
func (s *Shell) initCompleters() {
s.setCompleter(iCompleter{cmd: s.rootCmd, disabled: func() bool { return s.multiChoiceActive }})
}
func (s *Shell) setCompleter(completer readline.AutoCompleter) {
config := s.reader.scanner.Config.Clone()
config.AutoComplete = completer
s.reader.scanner.SetConfig(config)
}
// CustomCompleter allows use of custom implementation of readline.Autocompleter.
func (s *Shell) CustomCompleter(completer readline.AutoCompleter) {
s.customCompleter = true
s.setCompleter(completer)
}
// AddCmd adds a new command handler.
// This only adds top level commands.
func (s *Shell) AddCmd(cmd *Cmd) {
s.rootCmd.AddCmd(cmd)
}
// DeleteCmd deletes a top level command.
func (s *Shell) DeleteCmd(name string) {
s.rootCmd.DeleteCmd(name)
}
// NotFound adds a generic function for all inputs.
// It is called if the shell input could not be handled by any of the
// added commands.
func (s *Shell) NotFound(f func(*Context)) {
s.generic = f
}
// AutoHelp sets if ishell should trigger help message if
// a command's arg is "help". Defaults to true.
//
// This can be set to false for more control on how help is
// displayed.
func (s *Shell) AutoHelp(enable bool) {
s.autoHelp = enable
}
// Interrupt adds a function to handle keyboard interrupt (Ctrl-c).
// count is the number of consecutive times that Ctrl-c has been pressed.
// i.e. any input apart from Ctrl-c resets count to 0.
func (s *Shell) Interrupt(f func(c *Context, count int, input string)) {
s.interrupt = f
}
// EOF adds a function to handle End of File input (Ctrl-d).
// This overrides the default behaviour which terminates the shell.
func (s *Shell) EOF(f func(c *Context)) {
s.eof = f
}
// SetHistoryPath sets where readlines history file location. Use an empty
// string to disable history file. It is empty by default.
func (s *Shell) SetHistoryPath(path string) {
// Using scanner.SetHistoryPath doesn't initialize things properly and
// history file is never written. Simpler to just create a new readline
// Instance.
config := s.reader.scanner.Config.Clone()
config.HistoryFile = path
s.reader.scanner, _ = readline.NewEx(config)
}
// SetHomeHistoryPath is a convenience method that sets the history path
// in user's home directory.
func (s *Shell) SetHomeHistoryPath(path string) {
home := os.Getenv("HOME")
if runtime.GOOS == "windows" {
home = os.Getenv("USERPROFILE")
}
abspath := filepath.Join(home, path)
s.SetHistoryPath(abspath)
}
// SetOut sets the writer to write outputs to.
func (s *Shell) SetOut(writer io.Writer) {
s.writer = writer
}
func initSelected(init []int, max int) []int {
selectedMap := make(map[int]bool)
for _, i := range init {
if i < max {
selectedMap[i] = true
}
}
selected := make([]int, len(selectedMap))
i := 0
for k := range selectedMap {
selected[i] = k
i++
}
return selected
}
func toggle(selected []int, cur int) []int {
for i, s := range selected {
if s == cur {
return append(selected[:i], selected[i+1:]...)
}
}
return append(selected, cur)
}
func (s *Shell) multiChoice(options []string, text string, init []int, multiResults bool) []int {
s.multiChoiceActive = true
defer func() { s.multiChoiceActive = false }()
conf := s.reader.scanner.Config.Clone()
conf.DisableAutoSaveHistory = true
conf.FuncFilterInputRune = func(r rune) (rune, bool) {
switch r {
case 16:
return -1, true
case 14:
return -2, true
case 32:
return -3, true
}
return r, true
}
var selected []int
if multiResults {
selected = initSelected(init, len(options))
}
s.ShowPrompt(false)
defer s.ShowPrompt(true)
// TODO this may not work on windows.
s.Print("\033[?25l")
defer s.Print("\033[?25h")
cur := 0
if len(selected) > 0 {
cur = selected[len(selected)-1]
}
_, curRow, err := getPosition()
if err != nil {
return nil
}
_, maxRows, err := readline.GetSize(0)
if err != nil {
return nil
}
// allocate some space to be at the top of the screen
s.Printf("\033[%dS", curRow)
// move cursor to the top
// TODO it happens on every update, however, some trash appears in history without this line
s.Print("\033[0;0H")
offset := 0
update := func() {
strs := buildOptionsStrings(options, selected, cur)
if len(strs) > maxRows-1 {
strs = strs[offset : maxRows+offset-1]
}
s.Print("\033[0;0H")
// clear from the cursor to the end of the screen
s.Print("\033[0J")
s.Println(text)
s.Print(strings.Join(strs, "\n"))
}
var lastKey rune
refresh := make(chan struct{}, 1)
listener := func(line []rune, pos int, key rune) (newline []rune, newPos int, ok bool) {
lastKey = key
if key == -2 {
cur++
if cur >= maxRows+offset-1 {
offset++
}
if cur >= len(options) {
offset = 0
cur = 0
}
} else if key == -1 {
cur--
if cur < offset {
offset--
}
if cur < 0 {
if len(options) > maxRows-1 {
offset = len(options) - maxRows + 1
} else {
offset = 0
}
cur = len(options) - 1
}
} else if key == -3 {
if multiResults {
selected = toggle(selected, cur)
}
}
refresh <- struct{}{}
return
}
conf.Listener = readline.FuncListener(listener)
oldconf := s.reader.scanner.SetConfig(conf)
stop := make(chan struct{})
defer func() {
stop <- struct{}{}
s.Println()
}()
t := time.NewTicker(time.Millisecond * 200)
defer t.Stop()
go func() {
for {
select {
case <-stop:
return
case <-refresh:
update()
case <-t.C:
_, rows, _ := readline.GetSize(0)
if maxRows != rows {
maxRows = rows
update()
}
}
}
}()
s.ReadLine()
s.reader.scanner.SetConfig(oldconf)
// only handles Ctrl-c for now
// this can be broaden later
switch lastKey {
// Ctrl-c
case 3:
return []int{-1}
}
if multiResults {
return selected
}
return []int{cur}
}
func buildOptionsStrings(options []string, selected []int, index int) []string {
var strs []string
symbol := " ❯"
if runtime.GOOS == "windows" {
symbol = " >"
}
for i, opt := range options {
mark := "⬡ "
if selected == nil {
mark = " "
}
for _, s := range selected {
if s == i {
mark = "⬢ "
}
}
if i == index {
cyan := color.New(color.FgCyan).Add(color.Bold).SprintFunc()
strs = append(strs, cyan(symbol+mark+opt))
} else {
strs = append(strs, " "+mark+opt)
}
}
return strs
}
// IgnoreCase specifies whether commands should not be case sensitive.
// Defaults to false i.e. commands are case sensitive.
// If true, commands must be registered in lower cases.
func (s *Shell) IgnoreCase(ignore bool) {
s.ignoreCase = ignore
}
// ProgressBar returns the progress bar for the shell.
func (s *Shell) ProgressBar() ProgressBar {
return s.progressBar
}
func newContext(s *Shell, cmd *Cmd, args []string) *Context {
if cmd == nil {
cmd = &Cmd{}
}
return &Context{
Actions: s.Actions,
values: s.contextValues,
progressBar: copyShellProgressBar(s),
Args: args,
RawArgs: s.rawArgs,
Cmd: *cmd,
}
}
func copyShellProgressBar(s *Shell) ProgressBar {
sp := s.progressBar.(*progressBarImpl)
p := newProgressBar(s)
p.Indeterminate(sp.indeterminate)
p.Display(sp.display)
p.Prefix(sp.prefix)
p.Suffix(sp.suffix)
p.Final(sp.final)
p.Interval(sp.interval)
return p
}
func getPosition() (int, int, error) {
state, err := readline.MakeRaw(0)
if err != nil {
return 0, 0, err
}
defer readline.Restore(0, state)
fmt.Printf("\033[6n")
var out string
reader := bufio.NewReader(os.Stdin)
if err != nil {
return 0, 0, err
}
for {
b, err := reader.ReadByte()
if err != nil || b == 'R' {
break
}
if unicode.IsPrint(rune(b)) {
out += string(b)
}
}
var row, col int
_, err = fmt.Sscanf(out, "[%d;%d", &row, &col)
if err != nil {
return 0, 0, err
}
return col, row, nil
}