Fix help text for positional args with default and env var

This commit is contained in:
Hugo Hromic 2024-07-22 19:18:14 +01:00
parent 3de7278c4f
commit bf156d17a3
No known key found for this signature in database
GPG Key ID: 5CAFA8074D3F443B
2 changed files with 70 additions and 1 deletions

View File

@ -260,7 +260,7 @@ func (p *Parser) WriteHelpForSubcommand(w io.Writer, subcommand ...string) error
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 {
print(w, spec.placeholder, spec.help) print(w, spec.placeholder, spec.help, withDefault(spec.defaultString), withEnv(spec.env))
} }
} }

View File

@ -1015,3 +1015,72 @@ Commands:
p.WriteHelp(&help) p.WriteHelp(&help)
assert.Equal(t, expectedHelp[1:], help.String()) assert.Equal(t, expectedHelp[1:], help.String())
} }
func TestHelpShowsPositionalWithDefault(t *testing.T) {
expectedHelp := `
Usage: example [FOO]
Positional arguments:
FOO this is a positional with a default [default: bar]
Options:
--help, -h display this help and exit
`
var args struct {
Foo string `arg:"positional" default:"bar" help:"this is a positional with a default"`
}
p, err := NewParser(Config{Program: "example"}, &args)
require.NoError(t, err)
var help bytes.Buffer
p.WriteHelp(&help)
assert.Equal(t, expectedHelp[1:], help.String())
}
func TestHelpShowsPositionalWithEnv(t *testing.T) {
expectedHelp := `
Usage: example [FOO]
Positional arguments:
FOO this is a positional with an env variable [env: FOO]
Options:
--help, -h display this help and exit
`
var args struct {
Foo string `arg:"positional,env:FOO" help:"this is a positional with an env variable"`
}
p, err := NewParser(Config{Program: "example"}, &args)
require.NoError(t, err)
var help bytes.Buffer
p.WriteHelp(&help)
assert.Equal(t, expectedHelp[1:], help.String())
}
func TestHelpShowsPositionalWithDefaultAndEnv(t *testing.T) {
expectedHelp := `
Usage: example [FOO]
Positional arguments:
FOO this is a positional with a default and an env variable [default: bar, env: FOO]
Options:
--help, -h display this help and exit
`
var args struct {
Foo string `arg:"positional,env:FOO" default:"bar" help:"this is a positional with a default and an env variable"`
}
p, err := NewParser(Config{Program: "example"}, &args)
require.NoError(t, err)
var help bytes.Buffer
p.WriteHelp(&help)
assert.Equal(t, expectedHelp[1:], help.String())
}