From 75499b99cba4ef0eab75aedc8f89ba6f116a835d Mon Sep 17 00:00:00 2001 From: Nestor Oprysk Date: Thu, 3 Sep 2020 17:54:24 +0300 Subject: [PATCH] Improving the required flags error by using the pluralize util --- command.go | 13 ++++++++++++- command_test.go | 19 +++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/command.go b/command.go index 27d39d54..0a2e8348 100644 --- a/command.go +++ b/command.go @@ -1004,7 +1004,10 @@ func (c *Command) validateRequiredFlags() error { }) if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) + return fmt.Errorf(`required %s "%s" not set`, + pluralize("flag", len(missingFlagNames)), + strings.Join(missingFlagNames, `", "`), + ) } return nil } @@ -1662,3 +1665,11 @@ func (c *Command) updateParentsPflags() { c.parentsPflags.AddFlagSet(parent.PersistentFlags()) }) } + +func pluralize(name string, length int) string { + if length == 1 { + return name + } + + return name + "s" +} diff --git a/command_test.go b/command_test.go index 16cc41b4..88862cf5 100644 --- a/command_test.go +++ b/command_test.go @@ -742,6 +742,21 @@ func TestPersistentFlagsOnChild(t *testing.T) { } } +func TestRequiredFlag(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.Flags().String("foo1", "", "") + c.MarkFlagRequired("foo1") + + expected := fmt.Sprintf("required flag %q not set", "foo1") + + _, err := executeCommand(c) + got := err.Error() + + if got != expected { + t.Errorf("Expected error: %q, got: %q", expected, got) + } +} + func TestRequiredFlags(t *testing.T) { c := &Command{Use: "c", Run: emptyRun} c.Flags().String("foo1", "", "") @@ -750,7 +765,7 @@ func TestRequiredFlags(t *testing.T) { c.MarkFlagRequired("foo2") c.Flags().String("bar", "", "") - expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2") + expected := fmt.Sprintf("required flags %q, %q not set", "foo1", "foo2") _, err := executeCommand(c) got := err.Error() @@ -777,7 +792,7 @@ func TestPersistentRequiredFlags(t *testing.T) { parent.AddCommand(child) - expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2") + expected := fmt.Sprintf("required flags %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2") _, err := executeCommand(parent, "child") if err.Error() != expected {