-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.go
81 lines (67 loc) · 1.34 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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
//Cmd command structure
type Cmd struct {
Func func(string) error
}
//Shell interactive interface
type Shell struct {
CmdList map[string]Cmd
Done *bool
enableReport *bool
//show menu
enableMenu bool
}
//Init initilize interactive shell
func (s *Shell) Init() {
s.CmdList = make(map[string]Cmd)
s.enableMenu = false
}
//AddCmd set up command
func (s *Shell) AddCmd(cn string, f func(string) error) {
s.CmdList[cn] = Cmd{Func: f}
}
//Run invoke shell process
func (s *Shell) Run() {
var oldEnableReport bool
for *s.Done == false {
r := bufio.NewReader(os.Stdin)
txt, _ := r.ReadString('\n')
if txt == "\n" {
if s.enableMenu == false {
s.CmdList["help"].Func("")
s.enableMenu = true
oldEnableReport = *s.enableReport
*s.enableReport = false
} else {
s.enableMenu = false
*s.enableReport = oldEnableReport
fmt.Println("\033[H\033[2J")
}
} else {
str := strings.TrimSuffix(txt, "\n")
clist := strings.SplitN(str, " ", 2)
cmd, f := s.CmdList[clist[0]]
var param string
if len(clist) > 1 {
param = clist[1]
}
if f == true {
err := cmd.Func(param)
if err != nil {
fmt.Println("Err: ", err)
}
s.enableMenu = false
}
}
}
}
//Stop stop shell process
func (s *Shell) Stop() {
*s.Done = true
}