From 805db6776317b24c10da2f797b487ff14abc5326 Mon Sep 17 00:00:00 2001 From: Paul Holzinger Date: Mon, 29 Aug 2022 07:52:07 +0100 Subject: [PATCH] use errors.Is() to check for errors 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 Merge https://github.com/spf13/cobra/pull/1730 --- command.go | 2 +- command_test.go | 20 ++++++++++++++++++++ zulu_test.go | 12 ++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index 6cde916..bd757a1 100644 --- a/command.go +++ b/command.go @@ -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 } diff --git a/command_test.go b/command_test.go index 8708254..151575c 100644 --- a/command_test.go +++ b/command_test.go @@ -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. diff --git a/zulu_test.go b/zulu_test.go index 11c8d28..7811316 100644 --- a/zulu_test.go +++ b/zulu_test.go @@ -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)