Skip to content
Myr

Add Command's RemoveCommand method

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This method removes children commands of an existing command. This allows to build CLI clients that can be extended by 3rd party tools, for instance by adding commands _and replacing the “version” command_. For now the 1st defined command will be executed, so it is not possible to override an existing command. But anyway, deleting old command then adding a new one is the ultimate way to be certain there is no confusion.

authored by Étienne Vallette d'Osia · committed by spf13 · parent 2cb625e · Browse files · 1 file+34 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+34 added−0 removed

  • other:+34 added−0 removed

1 file+34 added−0 removed

modified:command.go+34 added
579 unmodified lines
580 c.commands = append(c.commands, x)581 }582}583584// AddCommand removes one or more commands from a parent command.585func (c *Command) RemoveCommand(cmds ...*Command) {586 commands := []*Command{}587main:588 for _, command := range c.commands {589 for _, cmd := range cmds {590 if command == cmd {591 command.parent = nil592 continue main593 }594 }595 commands = append(commands, command)596 }597 c.commands = commands598 // recompute all lengths599 c.commandsMaxUseLen = 0600 c.commandsMaxCommandPathLen = 0601 c.commandsMaxNameLen = 0602 for _, command := range c.commands {603 usageLen := len(command.Use)604 if usageLen > c.commandsMaxUseLen {605 c.commandsMaxUseLen = usageLen606 }607 commandPathLen := len(command.CommandPath())608 if commandPathLen > c.commandsMaxCommandPathLen {609 c.commandsMaxCommandPathLen = commandPathLen610 }611 nameLen := len(command.Name())612 if nameLen > c.commandsMaxNameLen {613 c.commandsMaxNameLen = nameLen614 }615 }616}617618// Convenience method to Print to the defined output619func (c *Command) Print(i ...interface{}) {620 fmt.Fprint(c.Out(), i...)621}
315 unmodified lines