Skip to content

Commit b9ca594

Browse files
authored
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 <[email protected]>
1 parent ea94a3d commit b9ca594

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

command.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package cobra
1818
import (
1919
"bytes"
2020
"context"
21+
"errors"
2122
"fmt"
2223
"io"
2324
"os"
@@ -990,7 +991,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
990991
if err != nil {
991992
// Always show help if requested, even if SilenceErrors is in
992993
// effect
993-
if err == flag.ErrHelp {
994+
if errors.Is(err, flag.ErrHelp) {
994995
cmd.HelpFunc()(cmd, args)
995996
return cmd, nil
996997
}

command_test.go

+32
Original file line numberDiff line numberDiff line change
@@ -1723,6 +1723,38 @@ func TestFlagErrorFunc(t *testing.T) {
17231723
}
17241724
}
17251725

1726+
func TestFlagErrorFuncHelp(t *testing.T) {
1727+
c := &Command{Use: "c", Run: emptyRun}
1728+
c.PersistentFlags().Bool("help", false, "help for c")
1729+
c.SetFlagErrorFunc(func(_ *Command, err error) error {
1730+
return fmt.Errorf("wrap error: %w", err)
1731+
})
1732+
1733+
out, err := executeCommand(c, "--help")
1734+
if err != nil {
1735+
t.Errorf("--help should not fail: %v", err)
1736+
}
1737+
1738+
expected := `Usage:
1739+
c [flags]
1740+
1741+
Flags:
1742+
--help help for c
1743+
`
1744+
if out != expected {
1745+
t.Errorf("Expected: %v, got: %v", expected, out)
1746+
}
1747+
1748+
out, err = executeCommand(c, "-h")
1749+
if err != nil {
1750+
t.Errorf("-h should not fail: %v", err)
1751+
}
1752+
1753+
if out != expected {
1754+
t.Errorf("Expected: %v, got: %v", expected, out)
1755+
}
1756+
}
1757+
17261758
// TestSortedFlags checks,
17271759
// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
17281760
// Related to https://github.com/spf13/cobra/issues/404.

0 commit comments

Comments
 (0)