-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.go
90 lines (74 loc) · 2.24 KB
/
shell.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
package ns
import (
"fmt"
"os"
"os/signal"
"syscall"
"golang.org/x/term"
)
type AutoComplete struct {
Name string
}
// Completer receives a string of everything before the cursor, after the cursor, and the entire command string. It
// returns a list of potential suggestions according to the available command set. Completers are invoked when the user
// presses <tab>, the completion key.
type Completer func(beforeCursor string, afterCursor string, full string) []*AutoComplete
// Executor is called when the <enter> key is pressed after inputting a command
type Executor func(ns *NilShell, cmd string)
type NilShell struct {
Prompt string
History *History
AutoCompleteLimit int // Maximum number of autocompletes to display
Debug bool
AutoCompleteSuggestStyle string
AutoCompleteTooMuchStyle string
preState *term.State
sigs chan os.Signal
lineReader *LineReader
onExecute Executor
isShutdown bool
}
// NewShell constructs a NilShell
func NewShell(prompt string, onComplete Completer, onExecute Executor) *NilShell {
sigs := make(chan os.Signal, 1)
ns := &NilShell{
Prompt: prompt,
History: NewHistory(100),
AutoCompleteLimit: 20,
sigs: sigs,
onExecute: onExecute,
}
ns.lineReader = NewLineReader(onComplete, sigs, ns)
signal.Notify(ns.sigs, syscall.SIGWINCH)
return ns
}
// ReadUntilTerm blocks, receiving commands until the user requests termination. Commands are processed via the executor callback
// provided at initialization time. Likewise for command completion.
func (n *NilShell) ReadUntilTerm() error {
for !n.isShutdown {
cmdString, isTerminate, err := n.lineReader.Read()
if err != nil {
return err
}
if isTerminate {
return nil
}
if len(cmdString) > 0 {
n.History.Append(cmdString)
fmt.Printf("\r")
n.onExecute(n, cmdString)
}
}
return nil
}
// Exit instructs the shell to gracefully exit - this can be safely invoked in an OnExecute method
// to implement a exit command
func (n *NilShell) Shutdown() {
n.sigs <- syscall.SIGTERM
n.isShutdown = true
}
// Clear will clear the terminal - this can be safely invoked in an OnExecute method
// to implement a clear command
func (n *NilShell) Clear() {
clear()
}