| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "slices" |
| 9 | "unicode" |
| 10 | ) |
| 11 | |
| 12 | type helpShownKey struct{} |
| 13 | |
| 14 | func (cmd *Command) parseArgsFromStdin() ([]string, error) { |
| 15 | type state int |
| 16 | const ( |
| 17 | stateSearchForToken state = -1 |
| 18 | stateSearchForString state = 0 |
| 19 | ) |
| 20 | |
| 21 | st := stateSearchForToken |
| 22 | linenum := 1 |
| 23 | token := "" |
| 24 | args := []string{} |
| 25 | |
| 26 | breader := bufio.NewReader(cmd.Reader) |
| 27 | |
| 28 | outer: |
| 29 | for { |
| 30 | ch, _, err := breader.ReadRune() |
| 31 | if err == io.EOF { |
| 32 | switch st { |
| 33 | case stateSearchForToken: |
| 34 | if token != "--" { |
| 35 | args = append(args, token) |
| 36 | } |
| 37 | case stateSearchForString: |
| 38 | // make sure string is not empty |
| 39 | for _, t := range token { |
| 40 | if !unicode.IsSpace(t) { |
| 41 | args = append(args, token) |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | break outer |
| 46 | } |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | switch st { |
| 51 | case stateSearchForToken: |
| 52 | if unicode.IsSpace(ch) || ch == '"' { |
| 53 | if ch == '\n' { |
| 54 | linenum++ |
| 55 | } |
| 56 | if token != "" { |
| 57 | // end the processing here |
| 58 | if token == "--" { |
| 59 | break outer |
| 60 | } |
| 61 | args = append(args, token) |
| 62 | token = "" |
| 63 | } |
| 64 | if ch == '"' { |
| 65 | st = stateSearchForString |
| 66 | } |
| 67 | continue |
| 68 | } |
| 69 | token += string(ch) |
| 70 | case stateSearchForString: |
| 71 | if ch != '"' { |
| 72 | token += string(ch) |
| 73 | } else { |
| 74 | if token != "" { |
| 75 | args = append(args, token) |
| 76 | token = "" |
| 77 | } |
| 78 | /*else { |
| 79 | //TODO. Should we pass in empty strings ? |
| 80 | }*/ |
| 81 | st = stateSearchForToken |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | tracef("parsed stdin args as %v (cmd=%[2]q)", args, cmd.Name) |
| 87 | |
| 88 | return args, nil |
| 89 | } |
| 90 | |
| 91 | // Run is the entry point to the command graph. The positional |
| 92 | // arguments are parsed according to the Flag and Command |
| 93 | // definitions and the matching Action functions are run. |
| 94 | func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) { |
| 95 | _, deferErr = cmd.run(ctx, osArgs) |
| 96 | return deferErr |
| 97 | } |
| 98 | |
| 99 | func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context, deferErr error) { |
| 100 | tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) |
| 101 | cmd.setupDefaults(osArgs) |
| 102 | |
| 103 | // Validate StopOnNthArg |
| 104 | if cmd.StopOnNthArg != nil && *cmd.StopOnNthArg < 0 { |
| 105 | return ctx, fmt.Errorf("StopOnNthArg must be non-negative, got %d", *cmd.StopOnNthArg) |
| 106 | } |
| 107 | |
| 108 | if v, ok := ctx.Value(commandContextKey).(*Command); ok { |
| 109 | tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name) |
| 110 | cmd.parent = v |
| 111 | } |
| 112 | |
| 113 | if cmd.parent == nil { |
| 114 | if cmd.ReadArgsFromStdin { |
| 115 | if args, err := cmd.parseArgsFromStdin(); err != nil { |
| 116 | return ctx, err |
| 117 | } else { |
| 118 | osArgs = append(osArgs, args...) |
| 119 | } |
| 120 | } |
| 121 | // handle the completion flag separately from the flagset since |
| 122 | // completion could be attempted after a flag, but before its value was put |
| 123 | // on the command line. this causes the flagset to interpret the completion |
| 124 | // flag name as the value of the flag before it which is undesirable |
| 125 | // note that we can only do this because the shell autocomplete function |
| 126 | // always appends the completion flag at the end of the command |
| 127 | tracef("checking osArgs %v (cmd=%[2]q)", osArgs, cmd.Name) |
| 128 | cmd.shellCompletion, osArgs = checkShellCompleteFlag(cmd, osArgs) |
| 129 | |
| 130 | tracef("setting cmd.shellCompletion=%[1]v from checkShellCompleteFlag (cmd=%[2]q)", cmd.shellCompletion && cmd.EnableShellCompletion, cmd.Name) |
| 131 | cmd.shellCompletion = cmd.EnableShellCompletion && cmd.shellCompletion |
| 132 | } |
| 133 | |
| 134 | tracef("using post-checkShellCompleteFlag arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) |
| 135 | |
| 136 | tracef("setting self as cmd in context (cmd=%[1]q)", cmd.Name) |
| 137 | ctx = context.WithValue(ctx, commandContextKey, cmd) |
| 138 | |
| 139 | if cmd.parent == nil { |
| 140 | cmd.setupCommandGraph() |
| 141 | } |
| 142 | |
| 143 | var rargs Args = &stringSliceArgs{v: osArgs} |
| 144 | var args Args = &stringSliceArgs{rargs.Tail()} |
| 145 | |
| 146 | for _, f := range cmd.allFlags() { |
| 147 | if cmd.hasPersistentFlagOnAncestor(f) { |
| 148 | continue |
| 149 | } |
| 150 | if err := f.PreParse(); err != nil { |
| 151 | return ctx, err |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | var err error |
| 156 | |
| 157 | if cmd.SkipFlagParsing { |
| 158 | tracef("skipping flag parsing (cmd=%[1]q)", cmd.Name) |
| 159 | cmd.parsedArgs = args |
| 160 | } else { |
| 161 | cmd.parsedArgs, err = cmd.parseFlags(args) |
| 162 | } |
| 163 | |
| 164 | tracef("using post-parse arguments %[1]q (cmd=%[2]q)", args, cmd.Name) |
| 165 | |
| 166 | if shouldRunCompletion(cmd) { |
| 167 | var beforeErr error |
| 168 | if ctx, beforeErr = runBefore(ctx, commandChain(cmd)); beforeErr != nil { |
| 169 | return ctx, beforeErr |
| 170 | } |
| 171 | runCompletion(ctx, cmd) |
| 172 | return ctx, nil |
| 173 | } |
| 174 | |
| 175 | if err != nil { |
| 176 | tracef("setting deferErr from %[1]q (cmd=%[2]q)", err, cmd.Name) |
| 177 | deferErr = err |
| 178 | |
| 179 | cmd.isInError = true |
| 180 | if cmd.checkHelp() { |
| 181 | ctx = context.WithValue(ctx, helpShownKey{}, true) |
| 182 | if cmd.parent == nil { |
| 183 | _ = ShowRootCommandHelp(cmd) |
| 184 | } else { |
| 185 | _ = ShowSubcommandHelp(cmd) |
| 186 | } |
| 187 | return ctx, nil |
| 188 | } |
| 189 | if cmd.OnUsageError != nil { |
| 190 | err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) |
| 191 | err = cmd.handleExitCoder(ctx, err) |
| 192 | return ctx, err |
| 193 | } |
| 194 | fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error()) |
| 195 | if cmd.Suggest { |
| 196 | if suggestion, err := cmd.suggestFlagFromError(err, ""); err == nil { |
| 197 | fmt.Fprintf(cmd.Root().ErrWriter, "%s", suggestion) |
| 198 | } |
| 199 | } |
| 200 | if !cmd.hideHelp() { |
| 201 | if cmd.parent == nil { |
| 202 | tracef("running ShowRootCommandHelp") |
| 203 | if err := ShowRootCommandHelp(cmd); err != nil { |
| 204 | tracef("SILENTLY IGNORING ERROR running ShowRootCommandHelp %[1]v (cmd=%[2]q)", err, cmd.Name) |
| 205 | } |
| 206 | } else { |
| 207 | tracef("running ShowSubcommandHelp for %[1]q", cmd.Name) |
| 208 | _ = ShowSubcommandHelp(cmd) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | return ctx, err |
| 213 | } |
| 214 | |
| 215 | if cmd.checkHelp() { |
| 216 | ctx = context.WithValue(ctx, helpShownKey{}, true) |
| 217 | return ctx, helpCommandAction(ctx, cmd) |
| 218 | } else { |
| 219 | tracef("no help is wanted (cmd=%[1]q)", cmd.Name) |
| 220 | } |
| 221 | |
| 222 | if cmd.parent == nil && !cmd.HideVersion && checkVersion(cmd) { |
| 223 | ShowVersion(cmd) |
| 224 | return ctx, nil |
| 225 | } |
| 226 | |
| 227 | for _, flag := range cmd.allFlags() { |
| 228 | cmd.setMultiValueParsingConfig(flag) |
| 229 | isSet := flag.IsSet() |
| 230 | if err := flag.PostParse(); err != nil { |
| 231 | return ctx, err |
| 232 | } |
| 233 | // add env set flags here |
| 234 | if !isSet && flag.IsSet() { |
| 235 | cmd.setFlags[flag] = struct{}{} |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | if cmd.After != nil && !cmd.Root().shellCompletion { |
| 240 | defer func() { |
| 241 | if ctx.Value(helpShownKey{}) != nil { |
| 242 | return |
| 243 | } |
| 244 | if err := cmd.After(ctx, cmd); err != nil { |
| 245 | err = cmd.handleExitCoder(ctx, err) |
| 246 | |
| 247 | if deferErr != nil { |
| 248 | deferErr = newMultiError(deferErr, err) |
| 249 | } else { |
| 250 | deferErr = err |
| 251 | } |
| 252 | } |
| 253 | }() |
| 254 | } |
| 255 | |
| 256 | // Walk the parent chain to check mutually exclusive flag groups |
| 257 | // defined on ancestor commands, since persistent flags are inherited. |
| 258 | for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent { |
| 259 | for _, grp := range pCmd.MutuallyExclusiveFlags { |
| 260 | if err := grp.check(cmd); err != nil { |
| 261 | if cmd.OnUsageError != nil { |
| 262 | err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) |
| 263 | } else { |
| 264 | fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error()) |
| 265 | if cmd.parent == nil { |
| 266 | _ = ShowRootCommandHelp(cmd) |
| 267 | } else { |
| 268 | if err := ShowCommandHelp(ctx, cmd.parent, cmd.Name); err != nil { |
| 269 | _ = ShowSubcommandHelp(cmd) |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | return ctx, err |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | var subCmd *Command |
| 279 | if cmd.parsedArgs.Present() { |
| 280 | tracef("checking positional args %[1]q (cmd=%[2]q)", cmd.parsedArgs, cmd.Name) |
| 281 | |
| 282 | name := cmd.parsedArgs.First() |
| 283 | |
| 284 | tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name) |
| 285 | |
| 286 | if cmd.SuggestCommandFunc != nil && name != "--" { |
| 287 | name = cmd.SuggestCommandFunc(cmd.Commands, name) |
| 288 | tracef("suggested command name=%1[q] (cmd=%[2]q)", name, cmd.Name) |
| 289 | } |
| 290 | subCmd = cmd.Command(name) |
| 291 | if subCmd == nil { |
| 292 | hasDefault := cmd.DefaultCommand != "" |
| 293 | |
| 294 | if hasDefault { |
| 295 | tracef("using default command=%[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) |
| 296 | } |
| 297 | |
| 298 | if hasDefault { |
| 299 | argsWithDefault := cmd.argsWithDefaultCommand(cmd.parsedArgs) |
| 300 | tracef("using default command args=%[1]q (cmd=%[2]q)", argsWithDefault, cmd.Name) |
| 301 | subCmd = cmd.Command(argsWithDefault.First()) |
| 302 | cmd.parsedArgs = argsWithDefault |
| 303 | } |
| 304 | } |
| 305 | } else if cmd.DefaultCommand != "" { |
| 306 | tracef("no positional args present; checking default command %[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) |
| 307 | |
| 308 | if dc := cmd.Command(cmd.DefaultCommand); dc != cmd { |
| 309 | subCmd = dc |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // If a subcommand has been resolved, let it handle the remaining execution. |
| 314 | if subCmd != nil { |
| 315 | tracef("running sub-command %[1]q with arguments %[2]q (cmd=%[3]q)", subCmd.Name, cmd.Args(), cmd.Name) |
| 316 | |
| 317 | // It is important that we overwrite the ctx variable in the current |
| 318 | // function so any defer'd functions use the new context returned |
| 319 | // from the sub command. |
| 320 | ctx, err = subCmd.run(ctx, cmd.Args().Slice()) |
| 321 | return ctx, err |
| 322 | } |
| 323 | |
| 324 | // This code path is the innermost command execution. Here we actually |
| 325 | // perform the command action. |
| 326 | // |
| 327 | // First, resolve the chain of nested commands up to the parent. |
| 328 | cmdChain := commandChain(cmd) |
| 329 | |
| 330 | // Run Before actions in order. |
| 331 | if ctx, err = runBefore(ctx, cmdChain); err != nil { |
| 332 | deferErr = err |
| 333 | return ctx, deferErr |
| 334 | } |
| 335 | |
| 336 | // Run flag actions in order. |
| 337 | // These take a context, so this has to happen after Before actions. |
| 338 | for _, cmd := range cmdChain { |
| 339 | tracef("running flag actions (cmd=%[1]q)", cmd.Name) |
| 340 | if err := cmd.runFlagActions(ctx); err != nil { |
| 341 | deferErr = cmd.handleExitCoder(ctx, err) |
| 342 | return ctx, deferErr |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | if err := cmd.checkAllRequiredFlags(); err != nil { |
| 347 | cmd.isInError = true |
| 348 | if cmd.OnUsageError != nil { |
| 349 | err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) |
| 350 | } else { |
| 351 | fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error()) |
| 352 | if cmd.parent == nil { |
| 353 | _ = ShowRootCommandHelp(cmd) |
| 354 | } else { |
| 355 | if err := ShowCommandHelp(ctx, cmd.parent, cmd.Name); err != nil { |
| 356 | _ = ShowSubcommandHelp(cmd) |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | return ctx, err |
| 361 | } |
| 362 | |
| 363 | // Run the command action. |
| 364 | if len(cmd.Arguments) > 0 { |
| 365 | rargs := cmd.Args().Slice() |
| 366 | tracef("calling argparse with %[1]v", rargs) |
| 367 | for _, arg := range cmd.Arguments { |
| 368 | var err error |
| 369 | rargs, err = arg.Parse(rargs) |
| 370 | if err != nil { |
| 371 | tracef("calling with %[1]v (cmd=%[2]q)", err, cmd.Name) |
| 372 | if cmd.OnUsageError != nil { |
| 373 | err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) |
| 374 | } |
| 375 | err = cmd.handleExitCoder(ctx, err) |
| 376 | return ctx, err |
| 377 | } |
| 378 | } |
| 379 | cmd.parsedArgs = &stringSliceArgs{v: rargs} |
| 380 | } |
| 381 | |
| 382 | if err := cmd.Action(ctx, cmd); err != nil { |
| 383 | tracef("calling handleExitCoder with %[1]v (cmd=%[2]q)", err, cmd.Name) |
| 384 | deferErr = cmd.handleExitCoder(ctx, err) |
| 385 | } |
| 386 | |
| 387 | tracef("returning deferErr (cmd=%[1]q) %[2]q", cmd.Name, deferErr) |
| 388 | return ctx, deferErr |
| 389 | } |
| 390 | |
| 391 | func commandChain(cmd *Command) []*Command { |
| 392 | var cmdChain []*Command |
| 393 | for p := cmd; p != nil; p = p.parent { |
| 394 | cmdChain = append(cmdChain, p) |
| 395 | } |
| 396 | slices.Reverse(cmdChain) |
| 397 | return cmdChain |
| 398 | } |
| 399 | |
| 400 | func runBefore(ctx context.Context, cmdChain []*Command) (context.Context, error) { |
| 401 | for _, cmd := range cmdChain { |
| 402 | if cmd.Before == nil { |
| 403 | continue |
| 404 | } |
| 405 | if bctx, err := cmd.Before(ctx, cmd); err != nil { |
| 406 | return ctx, cmd.handleExitCoder(ctx, err) |
| 407 | } else if bctx != nil { |
| 408 | ctx = bctx |
| 409 | } |
| 410 | } |
| 411 | return ctx, nil |
| 412 | } |