diff --git a/command.go b/command.go index b6e3f4a1c..00a6a26ce 100644 --- a/command.go +++ b/command.go @@ -1311,6 +1311,26 @@ func (c *Command) AddGroup(groups ...*Group) { c.commandgroups = append(c.commandgroups, groups...) } +// RemoveGroup removes command group from parent command. +func (c *Command) RemoveGroup(groupID string) bool { + index := c.getGroupIndex(groupID) + if index >= 0 { + c.commandgroups = append(c.commandgroups[:index], c.commandgroups[index+1:]...) + return true + } + return false +} + +// getGroupIndex returns index of groupID if it exists in the list of command groups else -1. +func (c *Command) getGroupIndex(groupID string) int { + for index, x := range c.commandgroups { + if x.ID == groupID { + return index + } + } + return -1 +} + // RemoveCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} diff --git a/command_test.go b/command_test.go index 18011325d..d0910f9a2 100644 --- a/command_test.go +++ b/command_test.go @@ -1862,6 +1862,24 @@ func TestAddGroup(t *testing.T) { checkStringContains(t, output, "\nTest group\n cmd") } +func TestRemoveGroup(t *testing.T) { + var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} + + rootCmd.AddGroup(&Group{ID: "group1", Title: "Test group 1"}) + rootCmd.AddGroup(&Group{ID: "group2", Title: "Test group 2"}) + rootCmd.AddGroup(&Group{ID: "group3", Title: "Test group 3"}) + rootCmd.AddGroup(&Group{ID: "group4", Title: "Test group 4"}) + + rootCmd.RemoveGroup("group2") + + for _, group := range rootCmd.Groups() { + if group.ID == "group2" { + t.Error(`Expected to not contain "group2"`) + } + } + +} + func TestWrongGroupFirstLevel(t *testing.T) { var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun} diff --git a/user_guide.md b/user_guide.md index 00b53d03c..c90db13a6 100644 --- a/user_guide.md +++ b/user_guide.md @@ -495,7 +495,7 @@ around it. In fact, you can provide your own if you want. Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element of that subcommand. The groups will appear in the help output in the same order as they are defined using different -calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using +calls to `AddGroup()`. To remove added groups you can use `RemoveGroup(groupID string)`. If you use the generated `help` or `completion` commands, you can set their group ids using `SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. ### Defining your own help