mirror of
https://github.com/spf13/cobra
synced 2024-12-28 07:17:06 +00:00
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:
parent
2cb625eda3
commit
f479c924b8
1 changed files with 34 additions and 0 deletions
34
command.go
34
command.go
|
@ -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...)
|
||||
|
|
Loading…
Reference in a new issue