/
cli.go
376 lines (339 loc) · 8.71 KB
/
cli.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
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
package xcli
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/kingwel-xie/readline"
"github.com/urfave/cli/v2"
)
var (
ErrBadArgument = fmt.Errorf("bad argument")
ErrQuitCLI = fmt.Errorf("quitting cli")
)
// built-in cli commands
//
var builtinCmds = cli.Commands{
&cli.Command{
Category: "builtin",
Name: "test",
Usage: "test",
Description: "test command cancellation",
Action: func(c *cli.Context) error {
done := make(chan struct{}, 1)
tick := time.NewTicker(time.Second)
go func() {
var count = 1
loop:
for {
select {
case <-tick.C:
fmt.Println("Tick...", count)
count++
if count >= 10 {
break loop
}
case <-c.Context.Done():
fmt.Fprintln(c.App.Writer, c.Context.Err())
break loop
}
}
done <- struct{}{}
}()
<-done
fmt.Fprintln(c.App.Writer, "Done")
return nil
},
},
&cli.Command{
Category: "builtin",
Name: "tree",
Usage: "tree",
Description: "show commands in tree",
Action: func(c *cli.Context) error {
rl := c.App.Metadata["readline"].(*readline.Instance)
tree := rl.Config.AutoComplete.(*readline.PrefixCompleter)
fmt.Fprint(c.App.Writer, tree.Tree(""))
return nil
},
},
&cli.Command{
Category: "builtin",
Name: "mode",
Usage: "mode [vi|emacs]",
Description: "set vi or emacs mode",
Action: func(c *cli.Context) error {
rl := c.App.Metadata["readline"].(*readline.Instance)
switch c.Args().First() {
case "vi":
rl.SetVimMode(true)
case "emacs":
rl.SetVimMode(false)
case "":
if rl.IsVimMode() {
fmt.Fprintln(c.App.Writer, "current mode: vim")
} else {
fmt.Fprintln(c.App.Writer, "current mode: emacs")
}
default:
return ErrBadArgument
}
return nil
},
},
&cli.Command{
Category: "builtin",
Name: "exit",
Aliases: []string{"quit"},
Usage: "exit",
Description: "exit CLI",
Action: func(c *cli.Context) error {
return ErrQuitCLI
},
},
}
func addChildren(parent *readline.PrefixCompleter, children ...readline.PrefixCompleterInterface) {
parent.Children = append(parent.Children, children...)
}
func generateCompleter(root *readline.PrefixCompleter, cmds cli.Commands) *readline.PrefixCompleter {
if root == nil {
root = readline.PcItem("")
// fix help
addChildren(root, readline.PcItem("help"))
}
for _, cmd := range cmds {
n := readline.PcItem(cmd.Name)
if cmd.Subcommands != nil {
generateCompleter(n, cmd.Subcommands)
}
addChildren(root, n)
}
return root
}
func filterInput(r rune) (rune, bool) {
switch r {
// block CtrlZ feature
case readline.CharCtrlZ:
return r, false
}
return r, true
}
func RunCli(cmds cli.Commands, f func(map[string]interface{})) {
fmt.Println("Spawning CLI...")
// install builtin commands
fullCmds := make(cli.Commands, 0, 100)
fullCmds = append(fullCmds, builtinCmds...)
fullCmds = append(fullCmds, cmds...)
completer := generateCompleter(nil, fullCmds)
//fmt.Println(completer.Tree(""))
//inDebugger := strings.Contains(os.Args[0], "go_build")
inDebugger := true
var prompt string
if inDebugger {
readline.Stdin = os.Stdin
readline.Stdout = os.Stdout
readline.Stderr = os.Stderr
prompt = "# "
} else {
prompt = "\033[31m$\033[0m "
}
// make rl at first, but without AutoComplete specified
rl, err := readline.NewEx(&readline.Config{
Prompt: prompt,
AutoComplete: completer,
InterruptPrompt: "interrupt",
EOFPrompt: "exit",
HistorySearchFold: true,
FuncFilterInputRune: filterInput,
})
if err != nil {
panic(err)
}
defer rl.Close()
// we close the stdio so that readline will quit the terminal ioloop
// dont close() here, we use os.Exit instead
//defer os.Stdin.Close()
// make cli app
app := setupCLI(fullCmds, rl, f)
// setup context
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
//log.SetOutput(rl.Stderr())
for {
ln := rl.Line()
if ln.CanBreak() {
fmt.Println(ln)
if inDebugger {
fmt.Println("Quit if in debugger, got", ln)
break
}
rl.SetPrompt("Do you really want to quit? [y/n]")
ln = rl.Line()
//ln = rl.Line()
if ln.Line == "Y" || ln.Line == "y" {
break
}
rl.SetPrompt(rl.Config.Prompt)
continue
}
//log.Println("readline:", ln.Line)
line := strings.TrimSpace(ln.Line)
var args []string = []string{"CLI"}
if line != "" {
cmdargs := strings.Fields(line)
args = append(args, cmdargs...)
}
// create command context
ctx, cancel := context.WithCancel(ctx)
done := make(chan struct{}, 1)
// routine to monitor the terminal for Break ^C ^D
go func() {
rl.Terminal.EnterRawMode()
f := rl.Config.FuncFilterInputRune
rl.Config.FuncFilterInputRune = func(r rune) (rune, bool) {
switch r {
case readline.CharInterrupt, readline.CharEnter, readline.CharCtrlJ, readline.CharDelete:
return r, true
}
// block all other runes
//fmt.Println("filtered", r)
return r, false
}
rl.SetPrompt("")
defer func() {
rl.Terminal.ExitRawMode()
rl.Config.FuncFilterInputRune = f
rl.SetPrompt(rl.Config.Prompt)
cancel()
done <- struct{}{}
//fmt.Println("DOne routine")
}()
for {
rl.Terminal.KickRead()
select {
case <-ctx.Done():
return
case <-rl.Operation.OutChan():
case err := <-rl.Operation.ErrChan():
if _, ok := err.(*readline.InterruptError); ok {
//fmt.Println("GOt int")
return
} else if err == io.EOF {
//fmt.Println("GOt eof")
return
} else {
//fmt.Println("GOt", err)
}
}
}
}()
e := app.RunContext(ctx, args)
if e != nil {
if e == ErrQuitCLI {
break
}
}
cancel()
// wait for monitor routine finished
<-done
//rl.Operation
//fmt.Println("DOne...")
}
os.Exit(1)
}
func setupCLI(cmds []*cli.Command, rl *readline.Instance, f func(map[string]interface{})) *cli.App {
cli.CommandHelpTemplate = `USAGE:
{{if .Usage}}{{.Usage}}{{else}}{{.Name}} {{end}}{{if .Category}}
CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}
`
cli.SubcommandHelpTemplate = `USAGE:
{{if .Usage}}{{.Usage}}{{else}}{{.Name}} {{end}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}
`
cli.AppHelpTemplate = `{{if .VisibleCommands}}COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
{{range $index, $option := .VisibleFlags}}{{if $index}}
{{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{.Copyright}}{{end}}{{if .Version}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
{{end}}{{$author}}{{end}}{{end}}
`
app := &cli.App{
Name: "xCLI",
Version: "v0.99.0",
Compiled: time.Now(),
Authors: []*cli.Author{
&cli.Author{
Name: "Kingwel Xie",
Email: "xie_jw@hisuntech.com",
},
},
//Copyright: "(c) 2020",
//Usage: "demonstrate available API",
//UsageText: "contrive - demonstrating the available API",
//ArgsUsage: "[args and such]",
Metadata: map[string]interface{}{
"readline": rl,
},
Commands: cmds,
//Writer: rl.Stdout(),
//Writer: rl.Stderr(),
HideHelp: false,
HideVersion: false,
Before: func(c *cli.Context) error {
//fmt.Fprintf(c.App.Writer, "CMD Begins\n")
return nil
},
After: func(c *cli.Context) error {
//fmt.Fprintf(c.App.Writer, "CMD Ends!\n")
return nil
},
CommandNotFound: func(c *cli.Context, command string) {
fmt.Fprintf(c.App.Writer, "No %q here.\n", command)
},
OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
if isSubcommand {
return err
}
fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err)
return nil
},
Action: func(c *cli.Context) error {
args := c.Args()
if args.Present() {
fmt.Fprintf(c.App.Writer, "%s : %s\n", "Unknown command", args.Slice())
}
return nil
},
ExitErrHandler: func(c *cli.Context, err error) {
if err != nil {
fmt.Fprintf(c.App.Writer, "Error : %s\n\n", err)
}
if c.Command != nil && err == ErrBadArgument {
cli.ShowCommandHelp(c, c.Command.Name)
}
},
}
// callback to set user specific data
if f != nil {
f(app.Metadata)
}
return app
}