refactor(cli): ensure namespace iter are alpha-ordered

This commit is contained in:
Marc 2024-01-28 14:01:36 -05:00
parent 1cfd60e9d7
commit 2c7225d44c
Signed by: marc
GPG key ID: 048E042F22B5DC79
2 changed files with 52 additions and 1 deletions

View file

@ -1,6 +1,7 @@
package cli package cli
import ( import (
"slices"
"strings" "strings"
logger "v/logger" logger "v/logger"
state "v/state" state "v/state"
@ -31,6 +32,18 @@ func (c *CLI) AddNamespace(namespace Namespace) *CLI {
return c return c
} }
func (c *CLI) ListNamespaces() []string {
labels := []string{}
for key := range c.Namespaces {
labels = append(labels, key)
}
slices.Sort(labels)
return labels
}
// Executes one of the registered commands if any match the provided // Executes one of the registered commands if any match the provided
// user arguments. // user arguments.
func (c CLI) Run(args []string, currentState state.State) error { func (c CLI) Run(args []string, currentState state.State) error {
@ -64,7 +77,8 @@ func (c CLI) Run(args []string, currentState state.State) error {
// and descriptions based on registered commands (see: AddCommand). // and descriptions based on registered commands (see: AddCommand).
func (c CLI) Help() { func (c CLI) Help() {
logger.InfoLogger.Printf("v: A simple version manager. (v%s)\n---", c.Metadata["Version"]) logger.InfoLogger.Printf("v: A simple version manager. (v%s)\n---", c.Metadata["Version"])
for _, namespace := range c.Namespaces { for _, namespaceLabel := range c.ListNamespaces() {
namespace := c.Namespaces[namespaceLabel]
for _, commandLabel := range namespace.ListCommands() { for _, commandLabel := range namespace.ListCommands() {
command := namespace.Commands[commandLabel] command := namespace.Commands[commandLabel]
logger.InfoLogger.Printf("\033[1m%-30s\033[0m%s\n", command.Usage, command.Description) logger.InfoLogger.Printf("\033[1m%-30s\033[0m%s\n", command.Usage, command.Description)

37
cli/cli_test.go Normal file
View file

@ -0,0 +1,37 @@
package cli
import (
"slices"
"testing"
)
func TestAddNamespace(t *testing.T) {
cli := CLI{}
namespace := Namespace{Label: "test"}
cli.AddNamespace(namespace)
if len(cli.Namespaces) != 1 {
t.Errorf("Expected one namespace added.")
}
if cli.Namespaces["test"].Label != namespace.Label {
t.Errorf("Unexpected label value: %s", cli.Namespaces["test"].Label)
}
}
func TestListNamespacesReturnsAlphaOrderedLabels(t *testing.T) {
cli := CLI{}
n1 := Namespace{Label: "a"}
n2 := Namespace{Label: "b"}
cli.AddNamespace(n2).AddNamespace(n1)
labels := cli.ListNamespaces()
if !slices.Equal(labels, []string{"a", "b"}) {
t.Errorf("Expected labels to be alpha ordered, got %v", labels)
}
}