Add groups for commands in help (#1003)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add tests for grouping commands * Adds Additional Command section in help
authored by aawsome · committed by GitHub · parent 212ea40 · Browse files · 5 files·+181 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
- Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
Diff stats
5 files+181 added−3 removed
- other:+181 added−3 removed
Provenance
- Commit
2169adb- Tree
d5966db- Author
aawsome <37850842+aawsome@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
212ea40
5 files changed+181 added−3 removed
modified:command_test.go+95 added
1765 unmodified lines1766 1767 EnableCommandSorting = defaultCommandSorting1768 }1769 1770+func TestUsageWithGroup(t *testing.T) {1771+ var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1772+ rootCmd.CompletionOptions.DisableDefaultCmd = true1773+1774+ rootCmd.AddGroup(&Group{ID: "group1", Title: "group1"})1775+ rootCmd.AddGroup(&Group{ID: "group2", Title: "group2"})1776+1777+ rootCmd.AddCommand(&Command{Use: "cmd1", GroupID: "group1", Run: emptyRun})1778+ rootCmd.AddCommand(&Command{Use: "cmd2", GroupID: "group2", Run: emptyRun})1779+1780+ output, err := executeCommand(rootCmd, "--help")1781+ if err != nil {1782+ t.Errorf("Unexpected error: %v", err)1783+ }1784+1785+ // help should be ungrouped here1786+ checkStringContains(t, output, "\nAdditional Commands:\n help")1787+ checkStringContains(t, output, "\ngroup1\n cmd1")1788+ checkStringContains(t, output, "\ngroup2\n cmd2")1789+}1790+1791+func TestUsageHelpGroup(t *testing.T) {1792+ var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1793+ rootCmd.CompletionOptions.DisableDefaultCmd = true1794+1795+ rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1796+ rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1797+ rootCmd.SetHelpCommandGroupID("group")1798+1799+ output, err := executeCommand(rootCmd, "--help")1800+ if err != nil {1801+ t.Errorf("Unexpected error: %v", err)1802+ }1803+1804+ // now help should be grouped under "group"1805+ checkStringOmits(t, output, "\nAdditional Commands:\n help")1806+ checkStringContains(t, output, "\ngroup\n help")1807+}1808+1809+func TestUsageCompletionGroup(t *testing.T) {1810+ var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1811+1812+ rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1813+ rootCmd.AddGroup(&Group{ID: "help", Title: "help"})1814+1815+ rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1816+ rootCmd.SetHelpCommandGroupID("help")1817+ rootCmd.SetCompletionCommandGroupID("group")1818+1819+ output, err := executeCommand(rootCmd, "--help")1820+ if err != nil {1821+ t.Errorf("Unexpected error: %v", err)1822+ }1823+1824+ // now completion should be grouped under "group"1825+ checkStringOmits(t, output, "\nAdditional Commands:\n completion")1826+ checkStringContains(t, output, "\ngroup\n completion")1827+}1828+1829+func TestUngroupedCommand(t *testing.T) {1830+ var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1831+1832+ rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1833+ rootCmd.AddGroup(&Group{ID: "help", Title: "help"})1834+1835+ rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1836+ rootCmd.SetHelpCommandGroupID("help")1837+ rootCmd.SetCompletionCommandGroupID("group")1838+1839+ // Add a command without a group1840+ rootCmd.AddCommand(&Command{Use: "yyy", Run: emptyRun})1841+1842+ output, err := executeCommand(rootCmd, "--help")1843+ if err != nil {1844+ t.Errorf("Unexpected error: %v", err)1845+ }1846+1847+ // The yyy command should be in the additional command "group"1848+ checkStringContains(t, output, "\nAdditional Commands:\n yyy")1849+}1850+1851+func TestAddGroup(t *testing.T) {1852+ var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1853+1854+ rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"})1855+ rootCmd.AddCommand(&Command{Use: "cmd", GroupID: "group", Run: emptyRun})1856+1857+ output, err := executeCommand(rootCmd, "--help")1858+ if err != nil {1859+ t.Errorf("Unexpected error: %v", err)1860+ }1861+1862+ checkStringContains(t, output, "\nTest group\n cmd")1863+}1864+1865 func TestSetOutput(t *testing.T) {1866 c := &Command{}1867 c.SetOutput(nil)1868 if out := c.OutOrStdout(); out != os.Stdout {659 unmodified linesmodified:command.go+77 added-3 removed
33 unmodified lines34 35 // FParseErrWhitelist configures Flag parse errors to be ignored36 type FParseErrWhitelist flag.ParseErrorsWhitelist37 38+// Structure to manage groups for commands39+type Group struct {40+ ID string41+ Title string42+}43+44 // Command is just that, a command for your application.45 // E.g. 'go run ...' - 'run' is the command. Cobra requires46 // you to define the usage and description as part of your command47 // definition to ensure usability.18 unmodified lines66 67 // Short is the short description shown in the 'help' output.68 Short string69 70+ // The group id under which this subcommand is grouped in the 'help' output of its parent.71+ GroupID string72+73 // Long is the long message shown in the 'help <this-command>' output.74 Long string75 76 // Example is examples of how to use the command.59 unmodified lines136 PersistentPostRun func(cmd *Command, args []string)137 // PersistentPostRunE: PersistentPostRun but returns an error.138 PersistentPostRunE func(cmd *Command, args []string) error139 140+ // groups for subcommands141+ commandgroups []*Group142+143 // args is actual args parsed from flags.144 args []string145 // flagErrorBuf contains all error messages from pflag.146 flagErrorBuf *bytes.Buffer24 unmodified lines171 helpFunc func(*Command, []string)172 // helpCommand is command with usage 'help'. If it's not defined by user,173 // cobra uses default help command.174 helpCommand *Command175+ // helpCommandGroupID is the group id for the helpCommand176+ helpCommandGroupID string177+178+ // completionCommandGroupID is the group id for the completion command179+ completionCommandGroupID string180+181 // versionTemplate is the version template defined by user.182 versionTemplate string183 184 // inReader is a reader defined by the user that replaces stdin135 unmodified lines320 func (c *Command) SetHelpCommand(cmd *Command) {321 c.helpCommand = cmd322 }323 324+// SetHelpCommandGroup sets the group id of the help command.325+func (c *Command) SetHelpCommandGroupID(groupID string) {326+ if c.helpCommand != nil {327+ c.helpCommand.GroupID = groupID328+ }329+ // helpCommandGroupID is used if no helpCommand is defined by the user330+ c.helpCommandGroupID = groupID331+}332+333+// SetCompletionCommandGroup sets the group id of the completion command.334+func (c *Command) SetCompletionCommandGroupID(groupID string) {335+ // completionCommandGroupID is used if no completion command is defined by the user336+ c.Root().completionCommandGroupID = groupID337+}338+339 // SetHelpTemplate sets help template to be used. Application can use it to set custom template.340 func (c *Command) SetHelpTemplate(s string) {341 c.helpTemplate = s342 }200 unmodified lines543 Aliases:544 {{.NameAndAliases}}{{end}}{{if .HasExample}}545 546 Examples:514-{{.Example}}{{end}}{{if .HasAvailableSubCommands}}547+{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}548 516-Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}517- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}549+Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}550+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}551 552+{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}553+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}554+555+Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}556+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}557+558 Flags:559 {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}560 561 Global Flags:616 unmodified lines1178 cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown1179 CheckErr(cmd.Help())1180 }1181 },1182+ GroupID: c.helpCommandGroupID,1183 }1184 }1185 c.RemoveCommand(c.helpCommand)1186 c.AddCommand(c.helpCommand)30 unmodified lines1217 if cmds[i] == c {1218 panic("Command can't be a child of itself")1219 }1220 cmds[i].parent = c1221+ // if Group is not defined let the developer know right away1222+ if x.GroupID != "" && !c.ContainsGroup(x.GroupID) {1223+ panic(fmt.Sprintf("Group id '%s' is not defined for subcommand '%s'", x.GroupID, cmds[i].CommandPath()))1224+ }1225 // update max lengths1226 usageLen := len(x.Use)1227 if usageLen > c.commandsMaxUseLen {1228 c.commandsMaxUseLen = usageLen14 unmodified lines1243 c.commandsAreSorted = false1244 }1245 }1246 1247+// Groups returns a slice of child command groups.1248+func (c *Command) Groups() []*Group {1249+ return c.commandgroups1250+}1251+1252+// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group1253+func (c *Command) AllChildCommandsHaveGroup() bool {1254+ for _, sub := range c.commands {1255+ if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {1256+ return false1257+ }1258+ }1259+ return true1260+}1261+1262+// ContainGroups return if groupID exists in the list of command groups.1263+func (c *Command) ContainsGroup(groupID string) bool {1264+ for _, x := range c.commandgroups {1265+ if x.ID == groupID {1266+ return true1267+ }1268+ }1269+ return false1270+}1271+1272+// AddGroup adds one or more command groups to this parent command.1273+func (c *Command) AddGroup(groups ...*Group) {1274+ c.commandgroups = append(c.commandgroups, groups...)1275+}1276+1277 // RemoveCommand removes one or more commands from a parent command.1278 func (c *Command) RemoveCommand(cmds ...*Command) {1279 commands := []*Command{}1280 main:517 unmodified linesmodified:completions.go+1 added
671 unmodified lines672 `, c.Root().Name()),673 Args: NoArgs,674 ValidArgsFunction: NoFileCompletions,675 Hidden: c.CompletionOptions.HiddenDefaultCmd,676+ GroupID: c.completionCommandGroupID,677 }678 c.AddCommand(completionCmd)679 680 out := c.OutOrStdout()191 unmodified linesmodified:README.md+1 added
21 unmodified lines22232425262728293082 unmodified lines21 unmodified lines* Nested subcommands* Global, local and cascading flags* Intelligent suggestions (`app srver`... did you mean `app server`?)* Automatic help generation for commands and flags* Grouping help for subcommands* Automatic help flag recognition of `-h`, `--help`, etc.* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)* Automatically generated man pages for your application* Command aliases so you can change things without breaking them82 unmodified linesmodified:user_guide.md+7 added
488 unmodified lines489 490 Help is just a command like any other. There is no special logic or behavior491 around it. In fact, you can provide your own if you want.492 493+### Grouping commands in help494+495+Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by496+the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined.497+If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId`498+and `SetCompletionCommandGroupId`, respectively.499+500 ### Defining your own help501 502 You can provide your own Help command or your own template for the default command to use503 with the following functions:191 unmodified lines