2024-01-26 05:56:37 +00:00
|
|
|
package cli
|
|
|
|
|
|
|
|
import (
|
2024-01-28 18:52:21 +00:00
|
|
|
"slices"
|
2024-01-26 05:56:37 +00:00
|
|
|
state "v/state"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Namespace struct {
|
2024-01-28 18:52:21 +00:00
|
|
|
Label string
|
|
|
|
Commands map[string]Command
|
2024-01-26 05:56:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Command definition for CLI subcommands.
|
|
|
|
type Command struct {
|
|
|
|
Label string
|
|
|
|
Handler func([]string, Flags, state.State) error
|
|
|
|
Usage string
|
|
|
|
Description string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Registers a command.
|
|
|
|
// This specifies a label that is used to route the user input to
|
|
|
|
// the right command, a handler that is called when the label is used,
|
|
|
|
// and usage/description details that get included in autogenerated help messaging.
|
|
|
|
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.Commands[label] = Command{Label: label, Handler: handler, Usage: usage, Description: description}
|
|
|
|
|
|
|
|
return n
|
|
|
|
}
|
2024-01-28 18:52:21 +00:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|