From 214a887b5ea73d6c367018677d318badf2e11dd0 Mon Sep 17 00:00:00 2001 From: Tugdual Saunier Date: Fri, 14 Jun 2024 14:29:54 +0200 Subject: [PATCH] fix: command.Names should not contain an empty string when command has no name or no alias --- command.go | 19 ++++++++++++------- command_test.go | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/command.go b/command.go index 20a4fd9..bed3e4f 100644 --- a/command.go +++ b/command.go @@ -92,14 +92,12 @@ func (c *Command) FullName() string { func (c *Command) PreferredName() string { name := c.FullName() - if len(c.Names()) > 1 { - // first alias is what we prefer - name = c.Names()[1] - } if name == "" && len(c.Aliases) > 0 { names := []string{} for _, a := range c.Aliases { - names = append(names, a.String()) + if name := a.String(); name != "" { + names = append(names, a.String()) + } } return strings.Join(names, ", ") } @@ -170,12 +168,19 @@ func (c *Command) Names() []string { if c.Category != "" { name = c.Category + ":" + name } - names := []string{name} + names := []string{} + if name != "" { + names = append(names, name) + } for _, a := range c.Aliases { - if !a.Hidden { + if a.Hidden { + continue + } + if name := a.String(); name != "" { names = append(names, a.String()) } } + return names } diff --git a/command_test.go b/command_test.go index ca25e7e..03e863b 100644 --- a/command_test.go +++ b/command_test.go @@ -23,6 +23,7 @@ import ( "errors" "flag" "io" + "reflect" "strings" "testing" @@ -146,3 +147,23 @@ func TestFuzzyCommandNames(t *testing.T) { t.Fatalf("expected no matches, got %v", c) } } + +func TestCommandWithNoNames(t *testing.T) { + c := Command{ + Aliases: []*Alias{ + {}, + {Name: "foo"}, + {Name: "bar"}, + }, + } + + if got, expected := c.Names(), []string{"foo", "bar"}; len(got) != 2 { + t.Fatalf("expected two names, got %v", len(got)) + } else if !reflect.DeepEqual(got, expected) { + t.Fatalf("expected %v, got %v", expected, got) + } + + if name := c.PreferredName(); name != "foo, bar" { + t.Fatalf(`expected "foo, bar", got "%v"`, name) + } +}