Files
commandkit/registry.go

36 lines
1000 B
Go

package commandkit
import "fmt"
// Register adds a batch of root commands to the application. The batch is
// validated before the registry is changed.
func (a *App) Register(commands ...Command) error {
if a == nil {
return fmt.Errorf("cannot register commands on a nil app")
}
pending := make(map[string]*commandNode, len(commands))
for _, command := range commands {
if err := validateCommandDeclaration(command); err != nil {
return err
}
if _, exists := a.commands[command.name]; exists {
return fmt.Errorf("command path %q is already registered", command.name)
}
if _, exists := pending[command.name]; exists {
return fmt.Errorf("command path %q is already registered", command.name)
}
pending[command.name] = &commandNode{command: cloneCommand(command)}
}
if len(pending) == 0 {
return nil
}
if a.commands == nil {
a.commands = make(map[string]*commandNode, len(pending))
}
for name, node := range pending {
a.commands[name] = node
}
return nil
}