From b9ca5949e2f58373e8e4c3823c213401f7d9d0e3 Mon Sep 17 00:00:00 2001 From: Paul Holzinger <45212748+Luap99@users.noreply.github.com> Date: Tue, 21 Jun 2022 04:02:33 +0200 Subject: [PATCH] use errors.Is() to check for errors (#1730) Since go 1.13 you can wrap errors. This make it no longer possible to compare with `==`, instead you have to compare with `errors.Is()`. I noticed this problem because -h was no longer working after I stared wrapping the errors in my custom FlagErrorFunc function. Note that this is only a problem when a custom help flag is defined. Signed-off-by: Paul Holzinger --- command.go | 3 ++- command_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index 3349be6..675bb13 100644 --- a/command.go +++ b/command.go @@ -18,6 +18,7 @@ package cobra import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -990,7 +991,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { if err != nil { // Always show help if requested, even if SilenceErrors is in // effect - if err == flag.ErrHelp { + if errors.Is(err, flag.ErrHelp) { cmd.HelpFunc()(cmd, args) return cmd, nil } diff --git a/command_test.go b/command_test.go index d48fef1..0446e3c 100644 --- a/command_test.go +++ b/command_test.go @@ -1723,6 +1723,38 @@ func TestFlagErrorFunc(t *testing.T) { } } +func TestFlagErrorFuncHelp(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.PersistentFlags().Bool("help", false, "help for c") + c.SetFlagErrorFunc(func(_ *Command, err error) error { + return fmt.Errorf("wrap error: %w", err) + }) + + out, err := executeCommand(c, "--help") + if err != nil { + t.Errorf("--help should not fail: %v", err) + } + + expected := `Usage: + c [flags] + +Flags: + --help help for c +` + if out != expected { + t.Errorf("Expected: %v, got: %v", expected, out) + } + + out, err = executeCommand(c, "-h") + if err != nil { + t.Errorf("-h should not fail: %v", err) + } + + if out != expected { + t.Errorf("Expected: %v, got: %v", expected, out) + } +} + // TestSortedFlags checks, // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. // Related to https://github.com/spf13/cobra/issues/404.