Skip to content

Commit

Permalink
Merge pull request #262 from hhromic/fix-261
Browse files Browse the repository at this point in the history
Fix help text for positional args with default and env var
  • Loading branch information
alexflint authored Sep 5, 2024
2 parents a5045bb + bf156d1 commit d10a064
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
2 changes: 1 addition & 1 deletion usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ func (p *Parser) WriteHelpForSubcommand(w io.Writer, subcommand ...string) error
if len(positionals) > 0 {
fmt.Fprint(w, "\nPositional arguments:\n")
for _, spec := range positionals {
print(w, spec.placeholder, spec.help)
print(w, spec.placeholder, spec.help, withDefault(spec.defaultString), withEnv(spec.env))
}
}

Expand Down
69 changes: 69 additions & 0 deletions usage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1015,3 +1015,72 @@ Commands:
p.WriteHelp(&help)
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())
}

0 comments on commit d10a064

Please sign in to comment.