From c6ba770ffda937f7343861146acf776577a30bcc Mon Sep 17 00:00:00 2001 From: Nick Miyake Date: Fri, 10 Nov 2017 09:37:15 -0800 Subject: [PATCH] Improve error message for missing required flags Make the error message distinguish between singular and plural to make it more human-readable. --- command.go | 6 +++++- command_test.go | 20 ++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/command.go b/command.go index 6cb64264..c50ab4e3 100644 --- a/command.go +++ b/command.go @@ -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 } diff --git a/command_test.go b/command_test.go index edffc150..cea3e99d 100644 --- a/command_test.go +++ b/command_test.go @@ -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 {