Skip to content

Commit

Permalink
fix: command.Names should not contain an empty string when command ha…
Browse files Browse the repository at this point in the history
…s no name or no alias
  • Loading branch information
tucksaun committed Jun 14, 2024
1 parent 4bda854 commit 214a887
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
19 changes: 12 additions & 7 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, ", ")
}
Expand Down Expand Up @@ -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
}

Expand Down
21 changes: 21 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"errors"
"flag"
"io"
"reflect"
"strings"
"testing"

Expand Down Expand Up @@ -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)
}
}

0 comments on commit 214a887

Please sign in to comment.