|
1 | 1 | package cli |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "flag" |
5 | | - "os" |
| 4 | + "flag" |
| 5 | + "os" |
6 | 6 | ) |
7 | 7 |
|
8 | 8 | func appendParent(parent string, add string) string { |
9 | | - if parent == "" { |
10 | | - return add + " " |
11 | | - } |
12 | | - return parent + add + " " |
| 9 | + if parent == "" { |
| 10 | + return add + " " |
| 11 | + } |
| 12 | + return parent + add + " " |
13 | 13 | } |
14 | 14 |
|
15 | | -// Run executes sets up flags, helps, and executes the command with the provided |
| 15 | +// Run sets up flags, helps, and executes the command with the provided |
16 | 16 | // arguments. |
17 | 17 | // |
18 | 18 | // parents is the list of parent commands. |
19 | 19 | // E.g the parent for `sail run hello` would be `sail run`. |
20 | 20 | // |
21 | 21 | // Use RunRoot if this package is managing the entire CLI. |
22 | 22 | func Run(cmd Command, args []string, parent string) { |
23 | | - fl := flag.NewFlagSet(parent+""+cmd.Spec().Name, flag.ExitOnError) |
24 | | - |
25 | | - if fc, ok := cmd.(FlaggedCommand); ok { |
26 | | - fc.RegisterFlags(fl) |
27 | | - } |
28 | | - |
29 | | - fl.Usage = func() { |
30 | | - renderHelp(cmd, fl, os.Stderr) |
31 | | - } |
32 | | - _ = fl.Parse(args) |
33 | | - |
34 | | - subcommandArg := fl.Arg(0) |
35 | | - |
36 | | - // Route to subcommand. |
37 | | - if pc, ok := cmd.(ParentCommand); ok && subcommandArg != "" { |
38 | | - for _, subcommand := range pc.Subcommands() { |
39 | | - if subcommand.Spec().Name != subcommandArg { |
40 | | - continue |
41 | | - } |
42 | | - |
43 | | - Run( |
44 | | - subcommand, fl.Args()[1:], |
45 | | - appendParent(parent, cmd.Spec().Name), |
46 | | - ) |
47 | | - return |
48 | | - } |
49 | | - } |
50 | | - |
51 | | - cmd.Run(fl) |
| 23 | + fl := flag.NewFlagSet(parent+""+cmd.Spec().Name, flag.ExitOnError) |
| 24 | + |
| 25 | + if fc, ok := cmd.(FlaggedCommand); ok { |
| 26 | + fc.RegisterFlags(fl) |
| 27 | + } |
| 28 | + |
| 29 | + fl.Usage = func() { |
| 30 | + renderHelp(cmd, fl, os.Stderr) |
| 31 | + } |
| 32 | + _ = fl.Parse(args) |
| 33 | + |
| 34 | + subcommandArg := fl.Arg(0) |
| 35 | + |
| 36 | + // Route to subcommand. |
| 37 | + if pc, ok := cmd.(ParentCommand); ok && subcommandArg != "" { |
| 38 | + for _, subcommand := range pc.Subcommands() { |
| 39 | + if subcommand.Spec().Name != subcommandArg { |
| 40 | + continue |
| 41 | + } |
| 42 | + |
| 43 | + Run( |
| 44 | + subcommand, fl.Args()[1:], |
| 45 | + appendParent(parent, cmd.Spec().Name), |
| 46 | + ) |
| 47 | + return |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + cmd.Run(fl) |
52 | 52 | } |
53 | 53 |
|
54 | 54 | // RunRoot calls Run with the process's arguments. |
55 | 55 | func RunRoot(cmd Command) { |
56 | | - Run(cmd, os.Args[1:], "") |
| 56 | + Run(cmd, os.Args[1:], "") |
57 | 57 | } |
0 commit comments