refactor(cli): remove ordered commands array, dynamically gather instead

This commit is contained in:
Marc 2024-01-28 13:52:21 -05:00
parent 18982b5a35
commit 1cfd60e9d7
Signed by: marc
GPG key ID: 048E042F22B5DC79
3 changed files with 37 additions and 6 deletions

View file

@ -65,7 +65,7 @@ func (c CLI) Run(args []string, currentState state.State) error {
func (c CLI) Help() {
logger.InfoLogger.Printf("v: A simple version manager. (v%s)\n---", c.Metadata["Version"])
for _, namespace := range c.Namespaces {
for _, commandLabel := range namespace.OrderedCommands {
for _, commandLabel := range namespace.ListCommands() {
command := namespace.Commands[commandLabel]
logger.InfoLogger.Printf("\033[1m%-30s\033[0m%s\n", command.Usage, command.Description)
}

View file

@ -1,13 +1,13 @@
package cli
import (
"slices"
state "v/state"
)
type Namespace struct {
Label string
Commands map[string]Command
OrderedCommands []string
Label string
Commands map[string]Command
}
// Command definition for CLI subcommands.
@ -25,11 +25,23 @@ type Command struct {
func (n *Namespace) AddCommand(label string, handler func([]string, Flags, state.State) error, usage string, description string) *Namespace {
if n.Commands == nil {
n.Commands = map[string]Command{}
n.OrderedCommands = []string{}
}
n.OrderedCommands = append(n.OrderedCommands, label)
n.Commands[label] = Command{Label: label, Handler: handler, Usage: usage, Description: description}
return n
}
// Returns an alpha-ordered list of commands in the namespace.
// The commands are returned as a list of command labels / actions.
func (n *Namespace) ListCommands() []string {
labels := []string{}
for key := range n.Commands {
labels = append(labels, key)
}
slices.Sort(labels)
return labels
}

View file

@ -1,6 +1,7 @@
package cli
import (
"slices"
"testing"
state "v/state"
)
@ -29,3 +30,21 @@ func TestNamespaceAddCommand(t *testing.T) {
t.Errorf("Expected canary value to have been modified.")
}
}
func TestNamespaceListCommandsReturnsAlphaSortedLabels(t *testing.T) {
namespace := Namespace{}
handler := func(a []string, b Flags, c state.State) error {
return nil
}
// Inserted in non-alpha order.
namespace.AddCommand("b", handler, "", "")
namespace.AddCommand("a", handler, "", "")
labels := namespace.ListCommands()
if !slices.Equal(labels, []string{"a", "b"}) {
t.Errorf("Expected labels to be alpha-ordered. Got %v", labels)
}
}