This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmdr.shell.go
executable file
·267 lines (233 loc) · 7.07 KB
/
cmdr.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
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
// Copyright © 2020 Hedzr Yeh.
package shell
import (
"bytes"
"fmt"
"github.com/c-bata/go-prompt"
"github.com/hedzr/cmdr"
"os"
"os/exec"
"strings"
)
// WithShellModule adds `shell` sub-command to cmdr system
func WithShellModule() cmdr.ExecOption {
return func(w *cmdr.ExecWorker) {
// daemonImpl = daemonImplX
w.AddOnBeforeXrefBuilding(func(root *cmdr.RootCommand, args []string) {
// if modifier != nil {
// root.SubCommands = append(root.SubCommands, modifier(DaemonServerCommand))
// } else {
// root.SubCommands = append(root.SubCommands, DaemonServerCommand)
// }
//
// // prefix = strings.Join(append(cmdr.RxxtPrefix, "server"), ".")
// // prefix = "server"
//
// attachPreAction(root, preAction)
// attachPostAction(root, postAction)
rootOpt := cmdr.NewCmdFrom(&root.Command)
shell := rootOpt.NewSubCommand().
Titles("shell", "sh").
Description("enable internal shell prompt mode", "").
Action(doShellModeAction)
shell.NewFlagV(true).Titles("demo-0", "0").ToggleGroup("Sample")
shell.NewFlagV(false).Titles("demo-1", "1").ToggleGroup("Sample")
shell.NewFlagV(false).Titles("demo-2", "2").ToggleGroup("Sample")
shell.NewFlagV(false).Titles("demo-3", "3").ToggleGroup("Sample")
shell.NewFlagV(false).Titles("demo-4", "4").ToggleGroup("Sample")
})
}
}
func doShellModeAction(cmd *cmdr.Command, args []string) (err error) {
// cmdr.Logger.Println(cmdr.GetStringR("shell.Sample"))
switch cmdr.GetStringR("shell.Sample") {
case "demo-0":
run0()
case "demo-1":
run1()
case "demo-2":
run2()
case "demo-3":
run3()
case "demo-4":
run4()
}
return
}
func run0() {
fmt.Println("cmdr shell prompt here...Type 'exit' or press 'Ctrl-D' to exit.")
p := prompt.New(executor,
completer,
prompt.OptionPrefix(">>> "),
prompt.OptionTitle("cmdr-prompt-mode here"),
)
p.Run()
}
func executor(in string) {
in = strings.TrimSpace(in)
if in == "" {
return
} else if in == "quit" || in == "exit" || in == "bye" {
os.Exit(0)
}
fmt.Println("Your input: " + in + " | for running " + cmdr.GetExecutablePath())
// cmd := exec.Command("/bin/sh", "-c", cmdr.GetExcutablePath()+" "+in)
// cmd.Stdin = os.Stdin
// cmd.Stdout = os.Stdout
// cmd.Stderr = os.Stderr
// if err := cmd.Run(); err != nil {
// fmt.Printf("Got error: %s\n", err.Error())
// }
}
func completer(in prompt.Document) []prompt.Suggest {
cmd, err := cmdr.Match(in.Text)
// var names string
// if cmd != nil {
// names = cmd.GetTitleNames()
// }
// cmdr.Logger.Debugf("in: %v, cmd: %q, err = %v", in, names, err)
if err != nil || cmd == nil {
return prompt.FilterHasPrefix([]prompt.Suggest{}, in.GetWordBeforeCursor(), true)
}
// cmdr.Logger.Debugf("cmd = %v", cmd)
return prompt.FilterHasPrefix(buildSuggestsFor(in.Text, cmd), in.GetWordBeforeCursor(), true)
}
func buildSuggestsFor(text string, command *cmdr.Command) (ret []prompt.Suggest) {
for _, cmd := range command.SubCommands {
ret = append(ret, prompt.Suggest{Text: cmd.GetTitleName(), Description: cmd.Description})
}
for _, flg := range command.Flags {
ret = append(ret, prompt.Suggest{Text: flg.GetTitleZshFlagName(), Description: flg.Description})
}
// var sa []string
// for _, r := range ret {
// sa = append(sa, r.Text)
// }
// cmdr.Logger.Debugf("%q: cmd.Titles: %q; ret: %v | %v", text, command.GetTitleNames(), len(ret), sa)
return
}
// ExecuteAndGetResult executes an command line string `s` and capture its outputs.
func ExecuteAndGetResult(s string) string {
s = strings.TrimSpace(s)
if s == "" {
cmdr.Logger.Debugf("you need to pass the something arguments")
return ""
}
out := &bytes.Buffer{}
cmd := exec.Command("/bin/sh", "-c", "kubectl "+s)
cmd.Stdin = os.Stdin
cmd.Stdout = out
if err := cmd.Run(); err != nil {
cmdr.Logger.Errorf("%v", err.Error())
return ""
}
r := string(out.Bytes())
return r
}
func run1() {
fmt.Println("A bash like sample 1...Type 'Ctrl-D' to exit.")
p := prompt.New(executor1,
completer1,
prompt.OptionPrefix(">>> "),
prompt.OptionTitle("sql-prompt for multi width characters"),
)
p.Run()
}
func executor1(in string) {
fmt.Println("Your input: " + in)
}
func completer1(in prompt.Document) []prompt.Suggest {
s := []prompt.Suggest{
{Text: "こんにちは", Description: "'こんにちは' means 'Hello' in Japanese"},
{Text: "감사합니다", Description: "'안녕하세요' means 'Hello' in Korean."},
{Text: "您好", Description: "'您好' means 'Hello' in Chinese."},
{Text: "Добрый день", Description: "'Добрый день' means 'Hello' in Russian."},
}
return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
}
func run2() {
fmt.Println("A bash like sample 2...Type 'Ctrl-D' to exit.")
in := prompt.Input(">>> ", completer2,
prompt.OptionTitle("sql-prompt"),
prompt.OptionHistory([]string{"SELECT * FROM users;"}),
prompt.OptionPrefixTextColor(prompt.Yellow),
prompt.OptionPreviewSuggestionTextColor(prompt.Blue),
prompt.OptionSelectedSuggestionBGColor(prompt.LightGray),
prompt.OptionSuggestionBGColor(prompt.DarkGray))
fmt.Println("Your input: " + in)
}
func completer2(in prompt.Document) []prompt.Suggest {
s := []prompt.Suggest{
{Text: "users", Description: "Store the username and age"},
{Text: "articles", Description: "Store the article text posted by user"},
{Text: "comments", Description: "Store the text commented to articles"},
{Text: "groups", Description: "Combine users with specific rules"},
}
return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
}
func run3() {
fmt.Println("A bash like sample: run external command...Type 'Ctrl-D' to exit.")
p := prompt.New(
executor3,
completer3,
)
p.Run()
}
func executor3(t string) {
if t == "bash" {
cmd := exec.Command("bash")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
} else {
cmd := exec.Command(t)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
return
}
func completer3(t prompt.Document) []prompt.Suggest {
return []prompt.Suggest{
{Text: "bash"},
}
}
func run4() {
p := prompt.New(
executor4,
completer4,
prompt.OptionPrefix(">>> "),
prompt.OptionLivePrefix(changeLivePrefix),
prompt.OptionTitle("live-prefix-example"),
)
p.Run()
}
// LivePrefixState is a struct for auto-completion
var LivePrefixState struct {
LivePrefix string
IsEnable bool
}
func executor4(in string) {
fmt.Println("Your input: " + in)
if in == "" {
LivePrefixState.IsEnable = false
LivePrefixState.LivePrefix = in
return
}
LivePrefixState.LivePrefix = in + "> "
LivePrefixState.IsEnable = true
}
func completer4(in prompt.Document) []prompt.Suggest {
s := []prompt.Suggest{
{Text: "users", Description: "Store the username and age"},
{Text: "articles", Description: "Store the article text posted by user"},
{Text: "comments", Description: "Store the text commented to articles"},
{Text: "groups", Description: "Combine users with specific rules"},
}
return prompt.FilterHasPrefix(s, in.GetWordBeforeCursor(), true)
}
func changeLivePrefix() (string, bool) {
return LivePrefixState.LivePrefix, LivePrefixState.IsEnable
}