Add support for setting a function to handle flag parsing errors.

The default pflag error is to only print the bad flag. This enables an application
to include a usage message or other details about the error.

Signed-off-by: Daniel Nephin <dnephin@gmail.com>
This commit is contained in:
Daniel Nephin
2016-05-25 14:27:02 -07:00
parent 9c28e4bbd7
commit 67feb8173c
3 changed files with 55 additions and 7 deletions

View File

@ -1,6 +1,8 @@
package cobra
import (
"bytes"
"fmt"
"os"
"reflect"
"testing"
@ -174,3 +176,27 @@ func TestEnableCommandSortingIsDisabled(t *testing.T) {
EnableCommandSorting = true
}
func TestFlagErrorFunc(t *testing.T) {
cmd := &Command{
Use: "print",
RunE: func(cmd *Command, args []string) error {
return nil
},
}
expectedFmt := "This is expected: %s"
cmd.SetFlagErrorFunc(func(c *Command, err error) error {
return fmt.Errorf(expectedFmt, err)
})
cmd.SetArgs([]string{"--bogus-flag"})
cmd.SetOutput(new(bytes.Buffer))
err := cmd.Execute()
expected := fmt.Sprintf(expectedFmt, "unknown flag: --bogus-flag")
if err.Error() != expected {
t.Errorf("expected %v, got %v", expected, err.Error())
}
}