diff --git a/cobra_test.go b/cobra_test.go index 5c98a603..629865c2 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -467,8 +467,16 @@ func TestRootHelp(t *testing.T) { t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) } + if strings.Contains(x.Output, cmdEcho.Use) { + t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) + } + x = fullSetupTest("echo --help") + if strings.Contains(x.Output, cmdTimes.Use) { + t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output) + } + checkResultContains(t, x, "Available Commands:") checkResultContains(t, x, "for more information about a command") diff --git a/command.go b/command.go index bf6f3c79..43091875 100644 --- a/command.go +++ b/command.go @@ -54,6 +54,7 @@ type Command struct { // max lengths of commands' string lengths for use in padding commandsMaxUseLen int commandsMaxCommandPathLen int + commandsMaxNameLen int flagErrorBuf *bytes.Buffer cmdErrorBuf *bytes.Buffer @@ -181,6 +182,16 @@ func (c *Command) CommandPathPadding() int { } } +var minNamePadding int = 11 + +func (c *Command) NamePadding() int { + if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { + return minNamePadding + } else { + return c.parent.commandsMaxNameLen + } +} + func (c *Command) UsageTemplate() string { if c.usageTemplate != "" { return c.usageTemplate @@ -198,7 +209,7 @@ Aliases: {{.NameAndAliases}}{{end}} {{ if .HasSubCommands}} Available Commands: {{range .Commands}}{{if .Runnable}} - {{rpad .Use .UsagePadding }} {{.Short}}{{end}}{{end}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}} {{end}} {{ if .HasLocalFlags}}Flags: {{.LocalFlags.FlagUsages}}{{end}} @@ -529,6 +540,10 @@ func (c *Command) AddCommand(cmds ...*Command) { if commandPathLen > c.commandsMaxCommandPathLen { c.commandsMaxCommandPathLen = commandPathLen } + nameLen := len(x.Name()) + if nameLen > c.commandsMaxNameLen { + c.commandsMaxNameLen = nameLen + } c.commands = append(c.commands, x) } }