Customizable error message prefix (#2023)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Souma · committed by GitHub · parent c5dacb3 · Browse files · 3 files·+61 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+61 added−2 removed
- other:+61 added−2 removed
Provenance
- Commit
0c72800- Tree
e2b5869- Author
Souma <101255979+5ouma@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c5dacb3
3 files changed+61 added−2 removed
modified:site/content/user_guide.md+6 added
594 unmodified lines595 Running an application with the '--version' flag will print the version to stdout using596 the version template. The template can be customized using the597 `cmd.SetVersionTemplate(s string)` function.598 599+## Error Message Prefix600+601+Cobra prints an error message when receiving a non-nil error value.602+The default error message is `Error: <error contents>`.603+The Prefix, `Error:` can be customized using the `cmd.SetErrPrefix(s string)` function.604+605 ## PreRun and PostRun Hooks606 607 It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:608 138 unmodified linesmodified:command_test.go+33 added
1097 unmodified lines1098 1099 checkStringContains(t, output, "customized version: 1.0.0")1100 }1101 1102+func TestRootErrPrefixExecutedOnSubcommand(t *testing.T) {1103+ rootCmd := &Command{Use: "root", Run: emptyRun}1104+ rootCmd.SetErrPrefix("root error prefix:")1105+ rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})1106+1107+ output, err := executeCommand(rootCmd, "sub", "--unknown-flag")1108+ if err == nil {1109+ t.Errorf("Expected error")1110+ }1111+1112+ checkStringContains(t, output, "root error prefix: unknown flag: --unknown-flag")1113+}1114+1115+func TestRootAndSubErrPrefix(t *testing.T) {1116+ rootCmd := &Command{Use: "root", Run: emptyRun}1117+ subCmd := &Command{Use: "sub", Run: emptyRun}1118+ rootCmd.AddCommand(subCmd)1119+ rootCmd.SetErrPrefix("root error prefix:")1120+ subCmd.SetErrPrefix("sub error prefix:")1121+1122+ if output, err := executeCommand(rootCmd, "--unknown-root-flag"); err == nil {1123+ t.Errorf("Expected error")1124+ } else {1125+ checkStringContains(t, output, "root error prefix: unknown flag: --unknown-root-flag")1126+ }1127+1128+ if output, err := executeCommand(rootCmd, "sub", "--unknown-sub-flag"); err == nil {1129+ t.Errorf("Expected error")1130+ } else {1131+ checkStringContains(t, output, "sub error prefix: unknown flag: --unknown-sub-flag")1132+ }1133+}1134+1135 func TestVersionFlagExecutedOnSubcommand(t *testing.T) {1136 rootCmd := &Command{Use: "root", Version: "1.0.0"}1137 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})1138 1632 unmodified linesmodified:command.go+22 added-2 removed
179 unmodified lines180 181 // versionTemplate is the version template defined by user.182 versionTemplate string183 184+ // errPrefix is the error message prefix defined by user.185+ errPrefix string186+187 // inReader is a reader defined by the user that replaces stdin188 inReader io.Reader189 // outWriter is a writer defined by the user that replaces stdout190 outWriter io.Writer157 unmodified lines348 func (c *Command) SetVersionTemplate(s string) {349 c.versionTemplate = s350 }351 352+// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.353+func (c *Command) SetErrPrefix(s string) {354+ c.errPrefix = s355+}356+357 // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.358 // The user should not have a cyclic dependency on commands.359 func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {360 c.Flags().SetNormalizeFunc(n)241 unmodified lines602 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}603 `604 }605 606+// ErrPrefix return error message prefix for the command607+func (c *Command) ErrPrefix() string {608+ if c.errPrefix != "" {609+ return c.errPrefix610+ }611+612+ if c.HasParent() {613+ return c.parent.ErrPrefix()614+ }615+ return "Error:"616+}617+618 func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {619 flag := fs.Lookup(name)620 if flag == nil {621 return false447 unmodified lines1069 if cmd != nil {1070 c = cmd1071 }1072 if !c.SilenceErrors {1053- c.PrintErrln("Error:", err.Error())1073+ c.PrintErrln(c.ErrPrefix(), err.Error())1074 c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())1075 }1076 return c, err1077 }20 unmodified lines1098 1099 // If root command has SilenceErrors flagged,1100 // all subcommands should respect it1101 if !cmd.SilenceErrors && !c.SilenceErrors {1082- c.PrintErrln("Error:", err.Error())1102+ c.PrintErrln(cmd.ErrPrefix(), err.Error())1103 }1104 1105 // If root command has SilenceUsage flagged,1106 // all subcommands should respect it750 unmodified lines