Files
commandkit/registry.go

41 lines
1.0 KiB
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 command.record.absent {
continue
}
name := command.record.name
if _, exists := a.commands[name]; exists {
return fmt.Errorf("command path %q is already registered", name)
}
if _, exists := pending[name]; exists {
return fmt.Errorf("command path %q is already registered", name)
}
pending[name] = &commandNode{command: 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
}
a.commandTree = nil
return nil
}