-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.go
571 lines (507 loc) · 14.9 KB
/
app.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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Roland Singer [roland.singer@deserbit.com]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jishell
import (
"fmt"
"github.com/chroblert/jishell/jconfig"
"github.com/jedib0t/go-pretty/v6/table"
"io"
"os"
"reflect"
"strings"
shlex "github.com/chroblert/go-shlex"
"github.com/desertbit/closer/v3"
"github.com/desertbit/readline"
"github.com/fatih/color"
)
// App is the entrypoint.
type App struct {
closer.Closer
rl *readline.Instance
config *Config
commands Commands
isShell bool
debug bool
currentPrompt string
flags Flags
flagMap FlagMap
args Args
initHook func(a *App, flags FlagMap) error
shellHook func(a *App) error
printHelp func(a *App, shell bool)
printCommandHelp func(a *App, cmd *Command, bIsShell, bHasArgs bool)
interruptHandler func(a *App, count int)
printASCIILogo func(a *App)
// JC0o0l Add
//currentCommandStr string
currentCmd *Command // JC 220520 存放当前的Command,初始为nil
previousCmd *Command // JC 220520 存放use切换前的Command,初始为nil
}
// New creates a new app.
// Panics if the config is invalid.
func New(c *Config) (a *App) {
// Prepare the config.
c.SetDefaults()
err := c.Validate()
if err != nil {
panic(err)
}
// APP.
a = &App{
Closer: closer.New(),
config: c,
currentPrompt: c.prompt(),
flagMap: make(FlagMap),
printHelp: defaultPrintHelp,
printCommandHelp: defaultPrintCommandHelp,
interruptHandler: defaultInterruptHandler,
//currentCommandStr: c.CurrentCmdStr,
currentCmd: nil,
}
// Register the builtin flags.
a.flags.Bool("h", "help", false, "display help")
a.flags.BoolL("nocolor", false, "disable color output")
a.flags.Bool("i", "interactive", false, "enable interactive mode")
a.flags.BoolL("debug", false, "display detail message.eg,flags and args")
// Register the user flags, if present.
if c.Flags != nil {
c.Flags(&a.flags)
}
return
}
// SetPrompt sets a new prompt.
func (a *App) SetPrompt(p string) {
if !a.config.NoColor {
p = a.config.PromptColor.Sprint(p)
}
a.currentPrompt = p
}
// GetPromp get a prompt string
func (a *App) GetPrompt() string {
return a.currentPrompt
}
//
//func (a *App) SetCurrentCommand(c string) {
// a.currentCommandStr = c
//}
//
//func (a *App) GetCurrentCommand() string {
// return a.currentCommandStr
//}
// SetDefaultPrompt resets the current prompt to the default prompt as
// configured in the config.
func (a *App) SetDefaultPrompt() {
a.currentPrompt = a.config.prompt()
}
// IsShell indicates, if this is a shell session.
func (a *App) IsShell() bool {
return a.isShell
}
// Config returns the app's config value.
func (a *App) Config() *Config {
return a.config
}
// Commands returns the app's commands.
// Access is not thread-safe. Only access during command execution.
func (a *App) Commands() *Commands {
return &a.commands
}
// PrintError prints the given error.
func (a *App) PrintError(err error) {
if a.config.NoColor {
a.Printf("error: %v\n", err)
} else {
a.config.ErrorColor.Fprint(a, "error: ")
a.Printf("%v\n", err)
}
}
// Print writes to terminal output.
// Print writes to standard output if terminal output is not yet active.
func (a *App) Print(args ...interface{}) (int, error) {
return fmt.Fprint(a, args...)
}
// Printf formats according to a format specifier and writes to terminal output.
// Printf writes to standard output if terminal output is not yet active.
func (a *App) Printf(format string, args ...interface{}) (int, error) {
return fmt.Fprintf(a, format, args...)
}
// Println writes to terminal output followed by a newline.
// Println writes to standard output if terminal output is not yet active.
func (a *App) Println(args ...interface{}) (int, error) {
return fmt.Fprintln(a, args...)
}
// OnInit sets the function which will be executed before the first command
// is executed. App flags can be handled here.
func (a *App) OnInit(f func(a *App, flags FlagMap) error) {
a.initHook = f
}
// OnShell sets the function which will be executed before the shell starts.
func (a *App) OnShell(f func(a *App) error) {
a.shellHook = f
}
// SetInterruptHandler sets the interrupt handler function.
func (a *App) SetInterruptHandler(f func(a *App, count int)) {
a.interruptHandler = f
}
// SetPrintHelp sets the print help function.
func (a *App) SetPrintHelp(f func(a *App, shell bool)) {
a.printHelp = f
}
// SetPrintCommandHelp sets the print help function for a single command.
func (a *App) SetPrintCommandHelp(f func(a *App, c *Command, shell bool, bHasArgs bool)) {
a.printCommandHelp = f
}
// SetPrintASCIILogo sets the function to print the ASCII logo.
func (a *App) SetPrintASCIILogo(f func(a *App)) {
a.printASCIILogo = func(a *App) {
if !a.config.NoColor {
a.config.ASCIILogoColor.Set()
defer color.Unset()
}
f(a)
}
}
// Write to the underlying output, using readline if available.
func (a *App) Write(p []byte) (int, error) {
return a.Stdout().Write(p)
}
// Stdout returns a writer to Stdout, using readline if available.
// Note that calling before Run() will return a different instance.
func (a *App) Stdout() io.Writer {
if a.rl != nil {
return a.rl.Stdout()
}
return os.Stdout
}
// Stderr returns a writer to Stderr, using readline if available.
// Note that calling before Run() will return a different instance.
func (a *App) Stderr() io.Writer {
if a.rl != nil {
return a.rl.Stderr()
}
return os.Stderr
}
// AddCommand adds a new command.
// Panics on error.
func (a *App) AddCommand(cmd *Command) {
a.addCommand(cmd, true)
}
// addCommand adds a new command.
// If addHelpFlag is true, a help flag is automatically
// added to the command which displays its usage on use.
// Panics on error.
func (a *App) addCommand(cmd *Command, addHelpFlag bool) {
err := cmd.validate()
if err != nil {
panic(err)
}
cmd.parentPath = "/" // JC 220521 为一级子命令设置prompt
cmd.registerFlagsAndArgs(addHelpFlag)
a.commands.Add(cmd)
}
// RunCommand runs a single command.
func (a *App) RunCommand(args []string) error {
// Parse the arguments string and obtain the command path to the root,
// and the command flags.
var (
cmds []*Command
flags FlagMap
//args []string
err error
)
if a.currentCmd == nil {
cmds, flags, args, err = a.commands.parse(args, a.flagMap, false)
} else {
var tmpCommands = Commands{}
for _, v := range a.commands.list {
if jconfig.CORE_COMMAND_STR == v.HelpGroup {
tmpCommands.Add(v)
}
}
for _, v := range a.currentCmd.commands.list {
tmpCommands.Add(v)
}
//tmpCommands = a.commands.
cmds, flags, args, err = tmpCommands.parse(args, a.flagMap, false)
}
if err != nil {
return err
} else if len(cmds) == 0 {
return fmt.Errorf("unknown command, try 'help'")
}
// The last command is the final command.
cmd := cmds[len(cmds)-1]
// Print the command help if the command run function is nil or if the help flag is set.
if flags.Bool("help") || cmd.Run == nil {
a.printCommandHelp(a, cmd, a.isShell, len(args) > 0 || len(flags) > 0)
return nil
}
//jlog.Warn("runCommand:",cmd.Name,cmd.isBuiltin)
//jlog.Error("args:",len(args),args)
// 如果该cmd不是内置命令,则处理args的双引号
if !cmd.isBuiltin {
for k, v := range args {
splitArgs, err := shlex.Split(v, true, false)
if err != nil {
return err
}
args[k] = splitArgs[0]
}
// 处理flag的双引号
for k, v := range flags {
//jlog.Info(reflect.TypeOf(v).Kind().String())
if reflect.TypeOf(v.Value).Kind().String() == "string" {
if len(v.Value.(string)) > 0 {
splitArgs, _ := shlex.Split(v.Value.(string), true, false)
flags[k] = &FlagMapItem{
Value: splitArgs[0],
IsDefault: false,
}
}
}
}
}
// Parse the arguments.
cmdArgMap := make(ArgMap)
args, err = cmd.args.parse(args, cmdArgMap)
if err != nil {
return err
}
// Check, if values from the argument string are not consumed (and therefore invalid).
if len(args) > 0 {
return fmt.Errorf("invalid usage of command '%s' (unconsumed input '%s'), try 'help'", cmd.Name, strings.Join(args, " "))
}
// Create the context and pass the rest args.
ctx := newContext(a, cmd, flags, cmdArgMap)
// JC 240521 如果开启了debug,则显示命令的flag和arg
if a.debug {
// flags中至少有一个help flag
if len(cmd.flags.list) > 1 || len(cmd.args.list) > 0 {
t := table.NewWriter()
t.AppendHeader(table.Row{"Name", "Value", "default", "type", "Description"})
// JC 240512 遍历输出flag
//tmpCommand := cmd
for _, v := range cmd.flags.list {
// JC 220514: 过滤掉help flag
if v.Long == "help" {
continue
}
t.AppendRow(table.Row{v.Long, flags[v.Long].Value, flags[v.Long].IsDefault, "flag", v.HelpArgs + ". " + v.Help})
}
t.AppendSeparator()
// JC 240522 遍历输出arg
for _, v := range cmd.args.list {
t.AppendRow(table.Row{v.Name, cmdArgMap[v.Name].Value, cmdArgMap[v.Name].IsDefault, "arg", v.HelpArgs + ". " + v.Help})
}
a.Println(t.Render())
}
}
// Run the command.
err = cmd.Run(ctx)
if err != nil {
return err
}
return nil
}
// Run the application and parse the command line arguments.
// This method blocks.
func (a *App) Run() (err error) {
defer a.Close()
// Sort all commands by their name.
a.commands.SortRecursive()
// TODO 有没有一种方法,能够接收控制台上输入的所有字符,而不是去掉双引号后的值
// Remove the program name from the args.
args := os.Args
if len(args) > 0 {
args = args[1:]
}
// 如果可执行程序后跟的第一个参数是 -i,则进入交互模式;默认是控制台模式
//if len(args) > 0 && args[0] == "-i"{
// a.isShell = true
// args = args[1:]
//}
// Parse the app command line flags.
args, err = a.flags.parse(args, a.flagMap)
if err != nil {
return err
}
// Check if nocolor was set.
a.config.NoColor = a.flagMap.Bool("nocolor")
// Determine if this is a shell session.
//a.isShell = len(args) == 0
// JC 220520 获取-i flag值
a.isShell = a.flagMap.Bool("interactive")
// JC 240521 获取--debug flag值
a.debug = a.flagMap.Bool("debug")
// JC 220520 再根据是否有别的参数,来设置是否为shell模式
//if len(args) > 0 {
// a.isShell = false
//}
//jlog.Error(len(args),args)
//jlog.Error(a.config.NoColor,a.isShell)
// Add shell builtin commands.
// Ensure to add all commands before running the init hook.
// If the init hook does something with the app commands, then these should also be included.
if a.isShell {
// Add shell builtin commands.
// Add general builtin commands.
// 添加help命令
a.addCommand(core_help(a), false)
// 添加exit命令
a.AddCommand(core_exit(a))
// 添加clear命令
a.AddCommand(core_clear(a))
// 添加use命令
a.AddCommand(core_use(a))
// 添加show命令
a.AddCommand(core_show(a))
// 添加setf命令
a.AddCommand(core_setf(a))
// 添加seta命令
a.AddCommand(core_seta(a))
// 添加run命令
a.AddCommand(core_run(a))
// 添加back命令
a.AddCommand(core_back(a))
// 添加unsetf命令
a.AddCommand(core_unsetf(a))
// 添加unseta命令
a.AddCommand(core_unseta(a))
}
// Run the init hook.
if a.initHook != nil {
err = a.initHook(a, a.flagMap)
if err != nil {
return err
}
}
// Check if a command chould be executed in non-interactive mode.
if !a.isShell {
// Check if help should be displayed.
if a.flagMap.Bool("help") {
a.printHelp(a, false)
return nil
}
return a.RunCommand(args)
}
// Create the readline instance.
a.rl, err = readline.NewEx(&readline.Config{
Prompt: a.currentPrompt,
HistorySearchFold: true, // enable case-insensitive history searching
DisableAutoSaveHistory: true,
HistoryFile: a.config.HistoryFile,
HistoryLimit: a.config.HistoryLimit,
AutoComplete: newCompleter(&a.commands, nil),
VimMode: a.config.VimMode,
})
if err != nil {
return err
}
a.OnClose(a.rl.Close)
// Run the shell hook.
if a.shellHook != nil {
err = a.shellHook(a)
if err != nil {
return err
}
}
// Print the ASCII logo.
if a.printASCIILogo != nil {
a.printASCIILogo(a)
}
// Run the shell.
return a.runShell()
}
func (a *App) runShell() error {
var interruptCount int
var lines []string
multiActive := false
Loop:
for !a.IsClosing() {
// Set the prompt.
if multiActive {
a.rl.SetPrompt(a.config.multiPrompt())
} else {
a.rl.SetPrompt(a.currentPrompt)
}
multiActive = false
// Readline.
line, err := a.rl.Readline()
//jlog.Error("line:",line)
if err != nil {
if err == readline.ErrInterrupt {
interruptCount++
a.interruptHandler(a, interruptCount)
continue Loop
} else if err == io.EOF {
return nil
} else {
return err
}
}
// Reset the interrupt count.
interruptCount = 0
// Handle multiline input.
if strings.HasSuffix(line, "\\") {
multiActive = true
line = strings.TrimSpace(line[:len(line)-1]) // Add without suffix and trim spaces.
lines = append(lines, line)
continue Loop
}
lines = append(lines, strings.TrimSpace(line))
line = strings.Join(lines, "")
line = strings.TrimSpace(line)
lines = lines[:0]
// Skip if the line is empty.
if len(line) == 0 {
continue Loop
}
// Save command history.
err = a.rl.SaveHistory(line)
if err != nil {
a.PrintError(err)
continue Loop
}
// Split the line to args.
args, err := shlex.Split(line, true, true)
//jlog.Error("line:",line,"args:",len(args),args)
if err != nil {
a.PrintError(fmt.Errorf("invalid args: %v", err))
continue Loop
}
// Execute the command.
err = a.RunCommand(args)
if err != nil {
a.PrintError(err)
// Do not continue the Loop here. We want to handle command changes below.
//continue Loop
}
// Sort the commands again if they have changed (Add or remove action).
if a.commands.hasChanged() {
a.commands.SortRecursive()
a.commands.unsetChanged()
}
}
return nil
}