From f479c924b8b0b70e1fa627a92405b6bb87d1097a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Vallette=20d=27Osia?= Date: Tue, 3 Mar 2015 15:50:53 +0900 Subject: [PATCH] Add Command's RemoveCommand method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- command.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/command.go b/command.go index b1b69e3..3538ccd 100644 --- a/command.go +++ b/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...)