11package cli
22
33import (
4- "flag"
5- "os"
4+ "flag"
5+ "os"
66)
77
88func 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 + " "
1313}
1414
1515// Run sets up flags, helps, and executes the command with the provided
@@ -20,38 +20,43 @@ func appendParent(parent string, add string) string {
2020//
2121// Use RunRoot if this package is managing the entire CLI.
2222func 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+
33+ if cmd .Spec ().RawArgs {
34+ // Use `--` to return immediately when parsing the flags.
35+ args = append ([]string {"--" }, args ... )
36+ }
37+ _ = fl .Parse (args )
38+
39+ subcommandArg := fl .Arg (0 )
40+
41+ // Route to subcommand.
42+ if pc , ok := cmd .(ParentCommand ); ok && subcommandArg != "" {
43+ for _ , subcommand := range pc .Subcommands () {
44+ if subcommand .Spec ().Name != subcommandArg {
45+ continue
46+ }
47+
48+ Run (
49+ subcommand , fl .Args ()[1 :],
50+ appendParent (parent , cmd .Spec ().Name ),
51+ )
52+ return
53+ }
54+ }
55+
56+ cmd .Run (fl )
5257}
5358
5459// RunRoot calls Run with the process's arguments.
5560func RunRoot (cmd Command ) {
56- Run (cmd , os .Args [1 :], "" )
61+ Run (cmd , os .Args [1 :], "" )
5762}
0 commit comments