Skip to content

Commit

Permalink
use errors.Is() to check for errors
Browse files Browse the repository at this point in the history
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 <pholzing@redhat.com>

Merge spf13/cobra#1730
  • Loading branch information
Luap99 authored and hoshsadiq committed Aug 29, 2022
1 parent 293eff2 commit 805db67
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion command.go
Expand Up @@ -1122,7 +1122,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {

// Always show help if requested, even if SilenceErrors is in
// effect
if err == zflag.ErrHelp {
if errors.Is(err, zflag.ErrHelp) {
cmd.HelpFunc()(cmd, args)
return cmd, nil
}
Expand Down
20 changes: 20 additions & 0 deletions command_test.go
Expand Up @@ -1824,6 +1824,26 @@ func TestFlagErrorFunc(t *testing.T) {
}
}

func TestFlagErrorFuncHelp(t *testing.T) {
t.Parallel()

c := &zulu.Command{Use: "c", RunE: emptyRun}
c.PersistentFlags().Bool("help", false, "help for c")
c.SetFlagErrorFunc(func(_ *zulu.Command, err error) error {
return fmt.Errorf("wrap error: %w", err)
})

expected := "Usage:\n c [flags]\n\nFlags:\n --help help for c\n"

out, err := executeCommand(c, "--help")
assertNoErr(t, err)
assertEqual(t, expected, out)

out, err = executeCommand(c, "-h")
assertNoErr(t, err)
assertEqual(t, 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.
Expand Down
12 changes: 12 additions & 0 deletions zulu_test.go
Expand Up @@ -7,6 +7,18 @@ import (
"github.com/gowarden/zulu"
)

func assertEqual(t *testing.T, expected, actual interface{}) {
t.Helper()
assertEqualf(t, expected, actual, "expected %[1]v with type %[1]T but got %[2]v with type %[2]T", expected, actual)
}

func assertEqualf(t *testing.T, expected, actual interface{}, msg string, fmt ...interface{}) {
t.Helper()
if expected != actual {
t.Errorf(msg, fmt...)
}
}

func assertNoErr(t *testing.T, e error) {
if e != nil {
t.Error(e)
Expand Down

0 comments on commit 805db67

Please sign in to comment.