Skip to content
Myr

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

5 files+181 added−3 removed

modified:command_test.go+95 added
1765 unmodified lines
17661767 EnableCommandSorting = defaultCommandSorting1768}17691770func TestUsageWithGroup(t *testing.T) {1771 var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1772 rootCmd.CompletionOptions.DisableDefaultCmd = true17731774 rootCmd.AddGroup(&Group{ID: "group1", Title: "group1"})1775 rootCmd.AddGroup(&Group{ID: "group2", Title: "group2"})17761777 rootCmd.AddCommand(&Command{Use: "cmd1", GroupID: "group1", Run: emptyRun})1778 rootCmd.AddCommand(&Command{Use: "cmd2", GroupID: "group2", Run: emptyRun})17791780 output, err := executeCommand(rootCmd, "--help")1781 if err != nil {1782 t.Errorf("Unexpected error: %v", err)1783 }17841785 // 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}17901791func TestUsageHelpGroup(t *testing.T) {1792 var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1793 rootCmd.CompletionOptions.DisableDefaultCmd = true17941795 rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1796 rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1797 rootCmd.SetHelpCommandGroupID("group")17981799 output, err := executeCommand(rootCmd, "--help")1800 if err != nil {1801 t.Errorf("Unexpected error: %v", err)1802 }18031804 // now help should be grouped under "group"1805 checkStringOmits(t, output, "\nAdditional Commands:\n help")1806 checkStringContains(t, output, "\ngroup\n help")1807}18081809func TestUsageCompletionGroup(t *testing.T) {1810 var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}18111812 rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1813 rootCmd.AddGroup(&Group{ID: "help", Title: "help"})18141815 rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1816 rootCmd.SetHelpCommandGroupID("help")1817 rootCmd.SetCompletionCommandGroupID("group")18181819 output, err := executeCommand(rootCmd, "--help")1820 if err != nil {1821 t.Errorf("Unexpected error: %v", err)1822 }18231824 // now completion should be grouped under "group"1825 checkStringOmits(t, output, "\nAdditional Commands:\n completion")1826 checkStringContains(t, output, "\ngroup\n completion")1827}18281829func TestUngroupedCommand(t *testing.T) {1830 var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}18311832 rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1833 rootCmd.AddGroup(&Group{ID: "help", Title: "help"})18341835 rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1836 rootCmd.SetHelpCommandGroupID("help")1837 rootCmd.SetCompletionCommandGroupID("group")18381839 // Add a command without a group1840 rootCmd.AddCommand(&Command{Use: "yyy", Run: emptyRun})18411842 output, err := executeCommand(rootCmd, "--help")1843 if err != nil {1844 t.Errorf("Unexpected error: %v", err)1845 }18461847 // The yyy command should be in the additional command "group"1848 checkStringContains(t, output, "\nAdditional Commands:\n yyy")1849}18501851func TestAddGroup(t *testing.T) {1852 var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}18531854 rootCmd.AddGroup(&Group{ID: "group", Title: "Test group"})1855 rootCmd.AddCommand(&Command{Use: "cmd", GroupID: "group", Run: emptyRun})18561857 output, err := executeCommand(rootCmd, "--help")1858 if err != nil {1859 t.Errorf("Unexpected error: %v", err)1860 }18611862 checkStringContains(t, output, "\nTest group\n cmd")1863}18641865func TestSetOutput(t *testing.T) {1866 c := &Command{}1867 c.SetOutput(nil)1868 if out := c.OutOrStdout(); out != os.Stdout {
659 unmodified lines
modified:command.go+77 added-3 removed
33 unmodified lines
3435// FParseErrWhitelist configures Flag parse errors to be ignored36type FParseErrWhitelist flag.ParseErrorsWhitelist3738// Structure to manage groups for commands39type Group struct {40 ID string41 Title string42}4344// 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 lines
6667 // Short is the short description shown in the 'help' output.68 Short string6970 // The group id under which this subcommand is grouped in the 'help' output of its parent.71 GroupID string7273 // Long is the long message shown in the 'help <this-command>' output.74 Long string7576 // Example is examples of how to use the command.
59 unmodified lines
136 PersistentPostRun func(cmd *Command, args []string)137 // PersistentPostRunE: PersistentPostRun but returns an error.138 PersistentPostRunE func(cmd *Command, args []string) error139140 // groups for subcommands141 commandgroups []*Group142143 // args is actual args parsed from flags.144 args []string145 // flagErrorBuf contains all error messages from pflag.146 flagErrorBuf *bytes.Buffer
24 unmodified lines
171 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 string177178 // completionCommandGroupID is the group id for the completion command179 completionCommandGroupID string180181 // versionTemplate is the version template defined by user.182 versionTemplate string183184 // inReader is a reader defined by the user that replaces stdin
135 unmodified lines
320func (c *Command) SetHelpCommand(cmd *Command) {321 c.helpCommand = cmd322}323324// SetHelpCommandGroup sets the group id of the help command.325func (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}332333// SetCompletionCommandGroup sets the group id of the completion command.334func (c *Command) SetCompletionCommandGroupID(groupID string) {335 // completionCommandGroupID is used if no completion command is defined by the user336 c.Root().completionCommandGroupID = groupID337}338339// SetHelpTemplate sets help template to be used. Application can use it to set custom template.340func (c *Command) SetHelpTemplate(s string) {341 c.helpTemplate = s342}
200 unmodified lines
543Aliases:544 {{.NameAndAliases}}{{end}}{{if .HasExample}}545546Examples:514{{.Example}}{{end}}{{if .HasAvailableSubCommands}}547{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}548516Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}517 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}549Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}550 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}551552{{.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}}554555Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}556 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}557558Flags:559{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}560561Global Flags:
616 unmodified lines
1178 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 lines
1217 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 = usageLen
14 unmodified lines
1243 c.commandsAreSorted = false1244 }1245}12461247// Groups returns a slice of child command groups.1248func (c *Command) Groups() []*Group {1249 return c.commandgroups1250}12511252// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group1253func (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}12611262// ContainGroups return if groupID exists in the list of command groups.1263func (c *Command) ContainsGroup(groupID string) bool {1264 for _, x := range c.commandgroups {1265 if x.ID == groupID {1266 return true1267 }1268 }1269 return false1270}12711272// AddGroup adds one or more command groups to this parent command.1273func (c *Command) AddGroup(groups ...*Group) {1274 c.commandgroups = append(c.commandgroups, groups...)1275}12761277// RemoveCommand removes one or more commands from a parent command.1278func (c *Command) RemoveCommand(cmds ...*Command) {1279 commands := []*Command{}1280main:
517 unmodified lines
modified:completions.go+1 added
671 unmodified lines
672`, c.Root().Name()),673 Args: NoArgs,674 ValidArgsFunction: NoFileCompletions,675 Hidden: c.CompletionOptions.HiddenDefaultCmd,676 GroupID: c.completionCommandGroupID,677 }678 c.AddCommand(completionCmd)679680 out := c.OutOrStdout()
191 unmodified lines
modified:README.md+1 added
modified:user_guide.md+7 added
488 unmodified lines
489490Help is just a command like any other. There is no special logic or behavior491around it. In fact, you can provide your own if you want.492493### Grouping commands in help494495Cobra supports grouping of available commands. Groups must be explicitly defined by `AddGroup` and set by496the `GroupId` element of a subcommand. The groups will appear in the same order as they are defined.497If you use the generated `help` or `completion` commands, you can set the group ids by `SetHelpCommandGroupId`498and `SetCompletionCommandGroupId`, respectively.499500### Defining your own help501502You can provide your own Help command or your own template for the default command to use503with the following functions:
191 unmodified lines