2026-10-07 13:16:52 +00:00
|
|
|
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 {
|
2026-10-11 01:22:47 +00:00
|
|
|
return a.installBatch(commands...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *App) installBatch(commands ...Command) error {
|
2026-10-07 13:16:52 +00:00
|
|
|
if a == nil {
|
|
|
|
|
return fmt.Errorf("cannot register commands on a nil app")
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-09 01:32:36 +00:00
|
|
|
pending := make(map[string]*commandNode, len(commands))
|
2026-10-07 13:16:52 +00:00
|
|
|
for _, command := range commands {
|
2026-10-11 01:22:47 +00:00
|
|
|
if err := validateCommandPlacement(command); err != nil {
|
2026-10-07 13:16:52 +00:00
|
|
|
return err
|
|
|
|
|
}
|
2026-10-11 01:15:13 +00:00
|
|
|
if command.record.absent {
|
|
|
|
|
continue
|
2026-10-09 01:32:36 +00:00
|
|
|
}
|
2026-10-11 01:15:13 +00:00
|
|
|
name := command.record.name
|
|
|
|
|
if _, exists := a.commands[name]; exists {
|
|
|
|
|
return fmt.Errorf("command path %q is already registered", name)
|
2026-10-07 13:16:52 +00:00
|
|
|
}
|
2026-10-11 01:15:13 +00:00
|
|
|
if _, exists := pending[name]; exists {
|
|
|
|
|
return fmt.Errorf("command path %q is already registered", name)
|
|
|
|
|
}
|
|
|
|
|
pending[name] = &commandNode{command: command}
|
2026-10-09 01:32:36 +00:00
|
|
|
}
|
|
|
|
|
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
|
2026-10-07 13:16:52 +00:00
|
|
|
}
|
2026-10-11 01:25:45 +00:00
|
|
|
a.snapshot = nil
|
2026-10-07 13:16:52 +00:00
|
|
|
return nil
|
|
|
|
|
}
|