help displays command names instead of usage in Available Commands

This commit is contained in:
Masahiro Sano 2015-02-11 18:20:29 +09:00
parent e1e66f7b4e
commit 6700cfc859
2 changed files with 24 additions and 1 deletions

View file

@ -467,8 +467,16 @@ func TestRootHelp(t *testing.T) {
t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) 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") 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, "Available Commands:")
checkResultContains(t, x, "for more information about that command") checkResultContains(t, x, "for more information about that command")

View file

@ -54,6 +54,7 @@ type Command struct {
// max lengths of commands' string lengths for use in padding // max lengths of commands' string lengths for use in padding
commandsMaxUseLen int commandsMaxUseLen int
commandsMaxCommandPathLen int commandsMaxCommandPathLen int
commandsMaxNameLen int
flagErrorBuf *bytes.Buffer flagErrorBuf *bytes.Buffer
cmdErrorBuf *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 { func (c *Command) UsageTemplate() string {
if c.usageTemplate != "" { if c.usageTemplate != "" {
return c.usageTemplate return c.usageTemplate
@ -198,7 +209,7 @@ Aliases:
{{.NameAndAliases}}{{end}} {{.NameAndAliases}}{{end}}
{{ if .HasSubCommands}} {{ if .HasSubCommands}}
Available Commands: {{range .Commands}}{{if .Runnable}} Available Commands: {{range .Commands}}{{if .Runnable}}
{{rpad .Use .UsagePadding }} {{.Short}}{{end}}{{end}} {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}
{{end}} {{end}}
{{ if .HasFlags}} Available Flags: {{ if .HasFlags}} Available Flags:
{{.Flags.FlagUsages}}{{end}}{{if .HasParent}}{{if and (gt .Commands 0) (gt .Parent.Commands 1) }} {{.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 { if commandPathLen > c.commandsMaxCommandPathLen {
c.commandsMaxCommandPathLen = commandPathLen c.commandsMaxCommandPathLen = commandPathLen
} }
nameLen := len(x.Name())
if nameLen > c.commandsMaxNameLen {
c.commandsMaxNameLen = nameLen
}
c.commands = append(c.commands, x) c.commands = append(c.commands, x)
} }
} }