Add Command's RemoveCommand method

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.
This commit is contained in:
Étienne Vallette d'Osia 2015-03-03 15:50:53 +09:00 committed by spf13
parent 2cb625eda3
commit f479c924b8

View File

@ -581,6 +581,40 @@ func (c *Command) AddCommand(cmds ...*Command) {
}
}
// AddCommand removes one or more commands from a parent command.
func (c *Command) RemoveCommand(cmds ...*Command) {
commands := []*Command{}
main:
for _, command := range c.commands {
for _, cmd := range cmds {
if command == cmd {
command.parent = nil
continue main
}
}
commands = append(commands, command)
}
c.commands = commands
// recompute all lengths
c.commandsMaxUseLen = 0
c.commandsMaxCommandPathLen = 0
c.commandsMaxNameLen = 0
for _, command := range c.commands {
usageLen := len(command.Use)
if usageLen > c.commandsMaxUseLen {
c.commandsMaxUseLen = usageLen
}
commandPathLen := len(command.CommandPath())
if commandPathLen > c.commandsMaxCommandPathLen {
c.commandsMaxCommandPathLen = commandPathLen
}
nameLen := len(command.Name())
if nameLen > c.commandsMaxNameLen {
c.commandsMaxNameLen = nameLen
}
}
}
// Convenience method to Print to the defined output
func (c *Command) Print(i ...interface{}) {
fmt.Fprint(c.Out(), i...)