Register validated commands without registry copies

This commit is contained in:
2026-10-09 01:32:36 +00:00
parent 3f8841f298
commit 5816dd3eb9
3 changed files with 50 additions and 10 deletions

View File

@@ -9,19 +9,27 @@ func (a *App) Register(commands ...Command) error {
return fmt.Errorf("cannot register commands on a nil app")
}
updated := make(map[string]*commandNode, len(a.commands)+len(commands))
for name, node := range a.commands {
updated[name] = node
}
pending := make(map[string]*commandNode, len(commands))
for _, command := range commands {
if err := validateCommandDeclaration(command); err != nil {
return err
}
if _, exists := updated[command.name]; exists {
if _, exists := a.commands[command.name]; exists {
return fmt.Errorf("command path %q is already registered", command.name)
}
updated[command.name] = &commandNode{command: cloneCommand(command)}
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
}
a.commands = updated
return nil
}