| 25 | } |
| 26 | |
| 27 | func run(ctx context.Context, args []string) error { |
| 28 | rootCmd := newRootCmd() |
| 29 | rootCmd.SetArgs(args) |
| 30 | err := rootCmd.ExecuteContext(ctx) |
| 31 | if err == nil { |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // On unknown commands or unknown flags, fall back to printing usage so |
| 36 | // the user sees what's available instead of a one-line cryptic error. |
| 37 | // Use the deepest subcommand that matched the args so flag errors show |
| 38 | // the relevant subcommand's usage, not the root. |
| 39 | msg := err.Error() |
| 40 | if strings.Contains(msg, "unknown command") || strings.Contains(msg, "unknown flag") || strings.Contains(msg, "unknown shorthand flag") { |
| 41 | target := rootCmd |
| 42 | if found, _, ferr := rootCmd.Find(args); ferr == nil && found != nil { |
| 43 | target = found |
| 44 | } |
| 45 | showUsage(target, err) |
| 46 | return errSilent |
| 47 | } |
| 48 | //nolint:wrapcheck // cobra surfaces errors that are already user-facing (RunE-prefixed or cobra arg validation); main prints them with an "error:" prefix |
| 49 | return err |
| 50 | } |
| 51 | |
| 52 | // errSilent signals that main should exit non-zero without re-printing the |
| 53 | // error (it has already been printed alongside the usage block). |