From 1cfd60e9d7a3a43f6723f718824631f3014c61b7 Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Sun, 28 Jan 2024 13:52:21 -0500 Subject: [PATCH] refactor(cli): remove ordered commands array, dynamically gather instead --- cli/cli.go | 2 +- cli/namespace.go | 22 +++++++++++++++++----- cli/namespace_test.go | 19 +++++++++++++++++++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/cli/cli.go b/cli/cli.go index 778e013..ead2055 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -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) } diff --git a/cli/namespace.go b/cli/namespace.go index 2bd734c..a590b04 100644 --- a/cli/namespace.go +++ b/cli/namespace.go @@ -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 +} diff --git a/cli/namespace_test.go b/cli/namespace_test.go index 28a6b01..fb32fb0 100644 --- a/cli/namespace_test.go +++ b/cli/namespace_test.go @@ -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) + } +}