From a16cb2499939d048b37ce4ad9488bb099a57fc2e Mon Sep 17 00:00:00 2001 From: Masahiro Sano Date: Wed, 11 Feb 2015 18:20:29 +0900 Subject: [PATCH] help displays command names instead of usage in Available Commands --- cobra_test.go | 8 ++++++++ command.go | 17 ++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/cobra_test.go b/cobra_test.go index 5c98a60..629865c 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 bf6f3c7..4309187 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) } }