Skip to content

Commit

Permalink
Merge pull request alecthomas#313 from autarch/autarch/env-var-in-help
Browse files Browse the repository at this point in the history
Add env var to --help output for flags and args
  • Loading branch information
alecthomas authored Mar 18, 2020
2 parents f024f0c + 3b53a4b commit f3beb11
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
14 changes: 14 additions & 0 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ func (f *FlagModel) FormatPlaceHolder() string {
return strings.ToUpper(f.Name)
}

func (f *FlagModel) HelpWithEnvar() string {
if f.Envar == "" {
return f.Help
}
return fmt.Sprintf("%s ($%s)", f.Help, f.Envar)
}

type ArgGroupModel struct {
Args []*ArgModel
}
Expand All @@ -114,6 +121,13 @@ func (a *ArgGroupModel) ArgSummary() string {
return strings.Join(out, " ")
}

func (a *ArgModel) HelpWithEnvar() string {
if a.Envar == "" {
return a.Help
}
return fmt.Sprintf("%s ($%s)", a.Help, a.Envar)
}

type ArgModel struct {
Name string
Help string
Expand Down
4 changes: 2 additions & 2 deletions usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent
}
for _, flag := range f {
if !flag.Hidden {
rows = append(rows, [2]string{formatFlag(haveShort, flag), flag.Help})
rows = append(rows, [2]string{formatFlag(haveShort, flag), flag.HelpWithEnvar()})
}
}
return rows
Expand Down Expand Up @@ -172,7 +172,7 @@ func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent
if !arg.Required {
s = "[" + s + "]"
}
rows = append(rows, [2]string{s, arg.Help})
rows = append(rows, [2]string{s, arg.HelpWithEnvar()})
}
}
return rows
Expand Down
13 changes: 13 additions & 0 deletions usage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,16 @@ func TestCmdClause_HelpLong(t *testing.T) {
usage := buf.String()
assert.Equal(t, "long help text", usage)
}

func TestArgEnvVar(t *testing.T) {
var buf bytes.Buffer

a := New("test", "Test").Writer(&buf).Terminate(nil)
a.Arg("arg", "Enable arg").Envar("ARG").String()
a.Flag("flag", "Enable flag").Envar("FLAG").String()

a.Parse([]string{"command", "--help"})
usage := buf.String()
assert.Contains(t, usage, "($ARG)")
assert.Contains(t, usage, "($FLAG)")
}

0 comments on commit f3beb11

Please sign in to comment.