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:
@ -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())
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user