From 6700cfc85967e7cab54a4e7c46730bdceccc141d 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 dd44812c..7a57ca06 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 that command") diff --git a/command.go b/command.go index a3a01ad5..03568141 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 .HasFlags}} Available Flags: {{.Flags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }} @@ -527,6 +538,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) } }