Add SetErrorTemplate() (#1)

* Add SetErrorTemplate()

* Use template instead of just a Printf string

* Update variable name for errorTemplate

* Undo unwanted change
This commit is contained in:
Sebastian Müller 2018-06-13 15:13:58 +02:00 committed by GitHub
parent 1e58aa3361
commit be64645f2f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 2 deletions

View file

@ -195,6 +195,8 @@ type Command struct {
helpCommand *Command
// versionTemplate is the version template defined by user.
versionTemplate string
// errorTemplate is the error template defined by user.
errorTemplate string
}
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
@ -219,6 +221,11 @@ func (c *Command) SetUsageTemplate(s string) {
c.usageTemplate = s
}
// SetErrorTemplate sets error template to be used. Application can use it to set custom template.
func (c *Command) SetErrorTemplate(s string) {
c.errorTemplate = s
}
// SetFlagErrorFunc sets a function to generate an error when flag parsing
// fails.
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
@ -434,6 +441,18 @@ func (c *Command) HelpTemplate() string {
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
}
// ErrorTemplate return error template for the command.
func (c *Command) ErrorTemplate() string {
if c.errorTemplate != "" {
return c.errorTemplate
}
if c.HasParent() {
return c.parent.ErrorTemplate()
}
return "Error: {{ .Error }}\n"
}
// VersionTemplate return version template for the command.
func (c *Command) VersionTemplate() string {
if c.versionTemplate != "" {
@ -838,7 +857,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
c = cmd
}
if !c.SilenceErrors {
c.Println("Error:", err.Error())
tmpl(c.OutOrStdout(), c.ErrorTemplate(), err)
c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
}
return c, err
@ -861,7 +880,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// If root command has SilentErrors flagged,
// all subcommands should respect it
if !cmd.SilenceErrors && !c.SilenceErrors {
c.Println("Error:", err.Error())
tmpl(c.OutOrStdout(), c.ErrorTemplate(), err)
}
// If root command has SilentUsage flagged,

View file

@ -866,6 +866,16 @@ func TestVersionTemplate(t *testing.T) {
checkStringContains(t, output, "customized version: 1.0.0")
}
func TestErrorTemplate(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
rootCmd.SetErrorTemplate(`customized error: {{ . }}`)
output, _ := executeCommand(rootCmd, "unknown")
checkStringContains(t, output, "customized error: unknown command")
}
func TestVersionFlagExecutedOnSubcommand(t *testing.T) {
rootCmd := &Command{Use: "root", Version: "1.0.0"}
rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})