Display help text for positional arguments

This commit is contained in:
brettlangdon 2015-11-21 18:59:40 -05:00
parent 5db9c77fa3
commit d45bd4523c
2 changed files with 39 additions and 3 deletions

View File

@ -68,11 +68,24 @@ func (p *Parser) WriteHelp(w io.Writer) {
p.WriteUsage(w) p.WriteUsage(w)
// the width of the left column
const colWidth = 25
// write the list of positionals // write the list of positionals
if len(positionals) > 0 { if len(positionals) > 0 {
fmt.Fprint(w, "\npositional arguments:\n") fmt.Fprint(w, "\npositional arguments:\n")
for _, spec := range positionals { for _, spec := range positionals {
fmt.Fprintf(w, " %s\n", spec.long) left := " " + spec.long
fmt.Fprint(w, left)
if spec.help != "" {
if len(left)+2 < colWidth {
fmt.Fprint(w, strings.Repeat(" ", colWidth-len(left)))
} else {
fmt.Fprint(w, "\n"+strings.Repeat(" ", colWidth))
}
fmt.Fprint(w, spec.help)
}
fmt.Fprint(w, "\n")
} }
} }

View File

@ -16,7 +16,7 @@ func TestWriteUsage(t *testing.T) {
positional arguments: positional arguments:
input input
output output positional output
options: options:
--verbose, -v verbosity level --verbose, -v verbosity level
@ -27,7 +27,7 @@ options:
` `
var args struct { var args struct {
Input string `arg:"positional"` Input string `arg:"positional"`
Output []string `arg:"positional"` Output []string `arg:"positional,help:positional output"`
Verbose bool `arg:"-v,help:verbosity level"` Verbose bool `arg:"-v,help:verbosity level"`
Dataset string `arg:"help:dataset to use"` Dataset string `arg:"help:dataset to use"`
Optimize int `arg:"-O,help:optimization level"` Optimize int `arg:"-O,help:optimization level"`
@ -45,3 +45,26 @@ options:
p.WriteHelp(&help) p.WriteHelp(&help)
assert.Equal(t, expectedHelp, help.String()) assert.Equal(t, expectedHelp, help.String())
} }
func TestUsageLongPositionalWithHelp(t *testing.T) {
expectedHelp := `usage: example VERYLONGPOSITIONALWITHHELP
positional arguments:
verylongpositionalwithhelp
this positional argument is very long
options:
--help, -h display this help and exit
`
var args struct {
VeryLongPositionalWithHelp string `arg:"positional,help:this positional argument is very long"`
}
p, err := NewParser(&args)
require.NoError(t, err)
os.Args[0] = "example"
var help bytes.Buffer
p.WriteHelp(&help)
assert.Equal(t, expectedHelp, help.String())
}