Skip to content
This repository was archived by the owner on Mar 4, 2025. It is now read-only.

Commit 0578428

Browse files
committed
Merge pull request #3 from VictorLowther/better-help-formatting
Don't make alignment look funny if commands are longer than 11 chars
2 parents 8a5cb9f + d4450ef commit 0578428

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

commands.go

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func (c *Commander) Run(args []string) error {
116116
}
117117

118118
func (c *Commander) usage() error {
119-
err := tmpl(os.Stderr, usageTemplate, c)
119+
err := tmpl(os.Stderr,strings.Replace(usageTemplate,"%%MAX%%",fmt.Sprintf("%d",c.MaxLen()),-1),c)
120120
if err != nil {
121121
fmt.Println(err)
122122
}
@@ -157,6 +157,23 @@ func (c *Commander) help(args []string) error {
157157
return fmt.Errorf("Unknown help topic %#q. Run '%v help'.\n", arg, c.Name)
158158
}
159159

160+
func (c *Commander) MaxLen() (res int) {
161+
res = 0
162+
for _,cmd := range c.Commands {
163+
i := len(cmd.Name())
164+
if i > res {
165+
res = i
166+
}
167+
}
168+
for _,cmd := range c.Commanders {
169+
i := len(cmd.Name)
170+
if i > res {
171+
res = i
172+
}
173+
}
174+
return
175+
}
176+
160177
// FullName returns the full name of the commander, prefixed with its parent commanders, if any.
161178
func (c *Commander) FullName() string {
162179
n := c.Name
@@ -226,20 +243,19 @@ func (c *Command) Runnable() bool {
226243
}
227244

228245
var usageTemplate = `Usage:
229-
230246
{{.Name}} command [arguments]
231247
232248
The commands are:
233249
{{range .Commands}}{{if .Runnable}}
234-
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
235-
{{range .Commanders}}
236-
{{.Name | printf "%-11s"}} {{.Short}}{{end}}
250+
{{.Name | printf "%-%%MAX%%s"}} {{.Short}}{{end}}{{end}}
251+
{{range $cmd := .Commanders}}
252+
{{.Name | printf "%-%%MAX%%s"}} {{.Short}}{{end}}
237253
238254
Use "{{$.Name}} help [command]" for more information about a command.
239255
240256
Additional help topics:
241-
{{range .Commands}}{{if not .Runnable}}
242-
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
257+
{{range $cmd := .Commands}}{{if not .Runnable}}
258+
{{.Name | printf "%-%%MAX%%s"}} {{.Short}}{{end}}{{end}}
243259
244260
Use "{{.Name}} help [topic]" for more information about that topic.
245261

0 commit comments

Comments
 (0)