Skip to content

Commit

Permalink
Improving the required flags error by using the pluralize util
Browse files Browse the repository at this point in the history
  • Loading branch information
noprysk-ua authored and nestoroprysk committed Oct 4, 2020
1 parent 02a0d2f commit 75499b9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
13 changes: 12 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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"
}
19 changes: 17 additions & 2 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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", "", "")
Expand All @@ -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()
Expand All @@ -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 {
Expand Down

0 comments on commit 75499b9

Please sign in to comment.