Improve error message for missing required flags

Make the error message distinguish between singular and plural
to make it more human-readable.
This commit is contained in:
Nick Miyake 2017-11-10 09:37:15 -08:00
parent 2da4a54c5c
commit c6ba770ffd
2 changed files with 23 additions and 3 deletions

View file

@ -823,7 +823,11 @@ func (c *Command) validateRequiredFlags() error {
})
if len(missingFlagNames) > 0 {
return fmt.Errorf(`Required flag(s) "%s" have/has not been set`, strings.Join(missingFlagNames, `", "`))
errFmtStr := `Required flags "%s" have not been set`
if len(missingFlagNames) == 1 {
errFmtStr = `Required flag "%s" has not been set`
}
return fmt.Errorf(errFmtStr, strings.Join(missingFlagNames, `", "`))
}
return nil
}

View file

@ -673,6 +673,22 @@ func TestPersistentFlagsOnChild(t *testing.T) {
}
}
func TestRequiredFlagsSingular(t *testing.T) {
c := &Command{Use: "c", Run: func(*Command, []string) {}}
output := new(bytes.Buffer)
c.SetOutput(output)
c.Flags().String("foo1", "", "required foo1")
c.MarkFlagRequired("foo1")
expected := fmt.Sprintf("Required flag %q has not been set", "foo1")
if err := c.Execute(); err != nil {
if err.Error() != expected {
t.Errorf("expected %v, got %v", expected, err.Error())
}
}
}
func TestRequiredFlags(t *testing.T) {
c := &Command{Use: "c", Run: emptyRun}
c.Flags().String("foo1", "", "")
@ -681,7 +697,7 @@ func TestRequiredFlags(t *testing.T) {
c.MarkFlagRequired("foo2")
c.Flags().String("bar", "", "")
expected := fmt.Sprintf("Required flag(s) %q, %q have/has not been set", "foo1", "foo2")
expected := fmt.Sprintf("Required flags %q, %q have not been set", "foo1", "foo2")
_, err := executeCommand(c)
got := err.Error()
@ -708,7 +724,7 @@ func TestPersistentRequiredFlags(t *testing.T) {
parent.AddCommand(child)
expected := fmt.Sprintf("Required flag(s) %q, %q, %q, %q have/has not been set", "bar1", "bar2", "foo1", "foo2")
expected := fmt.Sprintf("Required flags %q, %q, %q, %q have not been set", "bar1", "bar2", "foo1", "foo2")
_, err := executeCommand(parent, "child")
if err.Error() != expected {