/
shell.go
104 lines (94 loc) · 2.07 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package shell
import (
"fmt"
"io"
"strings"
"sync/atomic"
"github.com/chzyer/readline"
"github.com/ncode/pretty/sshConn"
"github.com/spf13/viper"
)
func usage(w io.Writer) {
io.WriteString(w, "commands:\n")
io.WriteString(w, completer.Tree(" "))
}
var completer = readline.NewPrefixCompleter(
readline.PcItem(":bye"),
readline.PcItem(":help"),
readline.PcItem(":status"),
readline.PcItem(":list"),
)
func filterInput(r rune) (rune, bool) {
switch r {
// block CtrlZ feature
case readline.CharCtrlZ:
return r, false
}
return r, true
}
func Spawn(hostList *sshConn.HostList) {
command := make(chan string)
sent := make(chan bool)
go sshConn.Broker(hostList, command, sent)
prompt := "pretty(0)>> "
rl, err := readline.NewEx(&readline.Config{
Prompt: prompt,
HistoryFile: viper.GetString("history_file"),
AutoComplete: completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",
HistorySearchFold: true,
FuncFilterInputRune: filterInput,
})
if err != nil {
panic(err)
}
defer rl.Close()
for {
line, err := rl.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
connected, waiting := hostList.State()
if waiting > 0 {
prompt = fmt.Sprintf("pretty(%d)/(%d)>> ", waiting, connected)
} else {
prompt = fmt.Sprintf("pretty(%d)>> ", connected)
}
rl.SetPrompt(prompt)
line = strings.TrimSpace(line)
switch {
case line == ":help":
usage(rl.Stderr())
case line == ":bye":
goto exit
case line == "exit":
goto exit
case line == ":list":
for _, host := range hostList.Hosts() {
var state bool
if atomic.LoadInt32(&host.IsConnected) == 1 {
state = true
}
fmt.Printf("%v: Connected(%v)\n", host.Hostname, state)
}
case line == ":status":
fmt.Printf("Connected hosts (%d)\n", connected)
fmt.Printf("Failed hosts (%d)\n", hostList.Len()-connected)
case line == "":
default:
if connected > 0 {
command <- line
<-sent
}
fmt.Printf(prompt)
}
}
exit:
}