-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.go
More file actions
442 lines (370 loc) · 8.81 KB
/
shell.go
File metadata and controls
442 lines (370 loc) · 8.81 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package gshell
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"github.com/chzyer/readline"
)
type Status string
const (
OK Status = "OK"
FAIL Status = "FAIL"
EXIT Status = "EXIT"
NOT_FOUND Status = "NOT_FOUND"
)
const (
SHELL_PROMPT = ">>> "
SHELL_PREFIX = "SHELL"
COMMAND_PREFIX = "COMMAND"
)
const (
COLOR_RED = "\033[31m"
COLOR_GREEN = "\033[32m"
COLOR_YELLOW = "\033[33m"
COLOR_BLUE = "\033[34m"
COLOR_MAGENTA = "\033[35m"
COLOR_CYAN = "\033[36m"
COLOR_RESET = "\033[0m"
)
type Shell struct {
commands map[string]*Command
rootCommand map[string]string
earlyExecCommands []EarlyCommand
inStream io.ReadCloser
outStream io.Writer
errStream io.Writer
inputHandler *InputHandler
prompt string
historyFile string
logger *Logger
exitFunc func()
}
type Option func(*Shell)
// Default to stdin
func WithInputStream(istream io.ReadCloser) Option {
return func(sh *Shell) {
sh.inStream = istream
}
}
// Default to stdout
func WithOutputStream(ostream io.Writer) Option {
return func(sh *Shell) {
sh.outStream = ostream
}
}
// Default to stderr
func WithErrorStream(errStream io.Writer) Option {
return func(sh *Shell) {
sh.errStream = errStream
}
}
// Default to ">>> "
func WithPrompt(prompt string) Option {
return func(sh *Shell) {
sh.prompt = prompt
}
}
// Default to ~/.gshell_history
func WithHistoryFile(historyFile string) Option {
return func(sh *Shell) {
sh.historyFile = historyFile
}
}
// Default to gshell.log
func WithLogger(logger *Logger) Option {
return func(sh *Shell) {
sh.logger = logger
}
}
// Default to nil
func WithExitFunc(exitFunc func()) Option {
return func(sh *Shell) {
sh.exitFunc = exitFunc
}
}
func New(options ...Option) *Shell {
sh := &Shell{
commands: make(map[string]*Command),
rootCommand: make(map[string]string),
}
for _, option := range options {
option(sh)
}
if sh.inStream == nil {
sh.inStream = readline.Stdin
}
if sh.outStream == nil {
sh.outStream = readline.Stdout
}
if sh.errStream == nil {
sh.errStream = readline.Stderr
}
if sh.prompt == "" {
sh.prompt = SHELL_PROMPT
}
if sh.historyFile == "" {
sh.historyFile = "~/.gshell_history"
}
if sh.logger == nil {
sh.logger = NewLogger("gshell.log")
}
listener := &KeyListener{shell: sh}
inputHandler, err := NewInputHandler(
sh.prompt,
sh.historyFile,
listener,
sh.inStream,
sh.outStream,
sh.errStream,
)
if err != nil {
panic(err)
}
sh.inputHandler = inputHandler
sh.registerBuiltInCommands()
return sh
}
func (sh *Shell) RegisterCommand(cmd *Command) {
for _, alias := range cmd.Aliases {
sh.addAlias(alias, cmd.Name)
}
sh.commands[cmd.Name] = cmd
}
func (sh *Shell) RegisterEarlyExecCommand(cmd EarlyCommand) {
sh.earlyExecCommands = append(sh.earlyExecCommands, cmd)
}
func (sh *Shell) GetCommands() []*Command {
var cmds []*Command
for _, cmd := range sh.commands {
cmds = append(cmds, cmd)
}
return cmds
}
func (sh *Shell) Error(prefix, err string) {
prefix = "[" + prefix + " Error]: " + err + "\n"
sh.WriteColored(COLOR_RED, prefix)
}
func (sh *Shell) Warn(prefix, warning string) {
prefix = "[" + prefix + " Warning]: " + warning + "\n"
sh.WriteColored(COLOR_YELLOW, prefix)
}
func (sh *Shell) Info(prefix, info string) {
prefix = "[" + prefix + " Info]: " + info + "\n"
sh.WriteColored(COLOR_BLUE, prefix)
}
func (sh *Shell) Success(prefix, success string) {
prefix = "[" + prefix + " Success]: " + success + "\n"
sh.WriteColored(COLOR_GREEN, prefix)
}
func (sh *Shell) WriteColored(color string, output string) {
if !isTerminal(sh.outStream) {
sh.Write(output)
return
}
sh.Write(string(color) + output + string(COLOR_RESET))
}
func (sh *Shell) Write(output string) {
_, _ = sh.outStream.Write([]byte(output))
}
func (sh *Shell) Run(welcMessage string) {
sh.clearScreen()
sh.Write(welcMessage)
sh.sortEarlyCommands()
for {
sh.Write("\n")
sh.executeEarlyCommands()
input, err := sh.inputHandler.ReadLine()
if err != nil {
if errors.Is(err, io.EOF) { // Ctrl+D to exit
break
}
sh.Error(SHELL_PREFIX, "Error reading input: "+err.Error())
continue
}
if sh.execute(&input) == EXIT {
break
}
}
sh.Exit()
}
func (sh *Shell) Exit() {
_ = sh.logger.Close()
sh.inputHandler.Close()
sh.inStream.Close()
if sh.exitFunc != nil {
sh.exitFunc()
}
}
/*
- Private methods
*/
func (sh *Shell) sortEarlyCommands() {
sort.SliceStable(sh.earlyExecCommands, func(i, j int) bool {
return sh.earlyExecCommands[i].Priority > sh.earlyExecCommands[j].Priority
})
}
func (sh *Shell) handleCommandOrAliasNotFound(cmd string) {
nearestCmd, matchedAlias := sh.getNearestCommandOrAlias(cmd)
if len(cmd) > 20 {
cmd = cmd[:20] + "..."
}
errMsg := "Command (" + cmd + ") not found, "
if nearestCmd != "" {
if matchedAlias != "" {
errMsg += "did you mean `" + matchedAlias + "` (alias for `" + nearestCmd + "`)?, "
} else {
errMsg += "did you mean `" + nearestCmd + "`?, "
}
}
errMsg += "type `help` for list of commands"
sh.Error(SHELL_PREFIX, errMsg)
sh.logger.Error(SHELL_PREFIX, errMsg)
}
func (sh *Shell) getNearestCommandOrAlias(cmd string) (string, string) {
best := 2
nearestCmd := ""
matchedAlias := ""
for _, c := range sh.commands {
dist := editDistance(c.Name, cmd)
if dist <= best {
best = dist
nearestCmd = c.Name
matchedAlias = ""
}
// Also check aliases
for _, alias := range c.Aliases {
dist := editDistance(alias, cmd)
if dist <= best {
best = dist
nearestCmd = c.Name
matchedAlias = alias
}
}
}
return nearestCmd, matchedAlias
}
func (sh *Shell) parseInput(input *string) (string, []string) {
tokens := strings.Fields(*input)
if len(tokens) == 0 {
return "", nil
}
return tokens[0], tokens[1:]
}
func (sh *Shell) executeEarlyCommands() {
for _, cmd := range sh.earlyExecCommands {
cmd.Handler(sh)
}
}
func (sh *Shell) autoCompleteCommand(cmd string) (string, bool) {
for c := range sh.commands {
if strings.HasPrefix(c, cmd) {
return c, true
}
}
return "", false
}
func (sh *Shell) autoCompleteArg(cmd, argPrefix string) (string, bool) {
if command, ok := sh.findCommandByNameOrAlias(cmd); ok {
for _, arg := range command.Args {
if arg.Tag != EMPTY_TAG {
if strings.HasPrefix(arg.Tag, argPrefix) {
return arg.Tag, true
}
}
}
}
return "", false
}
func (sh *Shell) executeCommand(cmdOrAlias string, args []string) Status {
if strings.ToUpper(cmdOrAlias) == string(EXIT) {
return EXIT
}
if cmdOrAlias == "" {
return OK
}
if command, ok := sh.findCommandByNameOrAlias(cmdOrAlias); ok {
ok, err := command.ValidateArgs(args)
if !ok {
sh.Error(COMMAND_PREFIX, "Invalid arguments, "+err.Error())
sh.logger.Error(SHELL_PREFIX, fmt.Sprintf("Invalid arguments for command %s: %s", cmdOrAlias, err))
return FAIL
}
stat, err := command.Handler(sh, args)
if err != nil {
sh.Error(COMMAND_PREFIX, err.Error())
sh.logger.Error(SHELL_PREFIX, fmt.Sprintf("Error executing command %s: %s", cmdOrAlias, err.Error()))
return FAIL
}
return stat
}
sh.logger.Error(SHELL_PREFIX, fmt.Sprintf("Command %s not found\n", cmdOrAlias))
return NOT_FOUND
}
func (sh *Shell) findCommandByNameOrAlias(cmdOrAlias string) (*Command, bool) {
if command, ok := sh.commands[cmdOrAlias]; ok {
return command, true
}
if command, ok := sh.rootCommand[cmdOrAlias]; ok {
return sh.commands[command], true
}
return &Command{}, false
}
func (sh *Shell) execute(input *string) Status {
commandOrAlias, args := sh.parseInput(input)
switch sh.executeCommand(commandOrAlias, args) {
case EXIT:
return EXIT
case FAIL:
command, found := sh.findCommandByNameOrAlias(commandOrAlias)
if !found {
sh.handleCommandOrAliasNotFound(commandOrAlias)
} else {
sh.Error(SHELL_PREFIX, "Command failed, Usage: "+command.Usage)
}
case NOT_FOUND:
sh.handleCommandOrAliasNotFound(commandOrAlias)
}
return OK
}
func (sh *Shell) read() string {
var input string
buf := make([]byte, 1024)
for {
n, err := sh.inStream.Read(buf)
if n > 0 {
input += string(buf[:n])
}
if err != nil || n == 0 || buf[n-1] == '\n' {
break
}
}
return input
}
func (sh *Shell) clearScreen() {
switch runtime.GOOS {
case "windows":
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
_ = cmd.Run()
default:
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
_ = cmd.Run()
}
if sh.inputHandler.reader != nil {
sh.inputHandler.reader.Refresh()
}
}
func (sh *Shell) addAlias(alias string, cmd string) {
if exsistCmd, ok := sh.rootCommand[alias]; ok {
warn := fmt.Sprintf("Alias %s already exists for command %s, alias overrided.", alias, sh.commands[exsistCmd].Name)
sh.Warn(COMMAND_PREFIX, warn)
sh.logger.Warn(SHELL_PREFIX, warn)
}
sh.rootCommand[alias] = cmd
}