Skip to content

Commit

Permalink
ffcli: DefaultUsageText: print valid defaults for bool flags (#79)
Browse files Browse the repository at this point in the history
* ffcli: DefaultUsageText: print valid defaults for bool flags

* ffcli: fix test for new DefaultUsageFunc output
  • Loading branch information
peterbourgon authored Apr 7, 2021
1 parent 76b11f3 commit 556df77
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
17 changes: 15 additions & 2 deletions ffcli/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,20 +226,33 @@ func DefaultUsageFunc(c *Command) string {
fmt.Fprintf(&b, "FLAGS\n")
tw := tabwriter.NewWriter(&b, 0, 2, 2, ' ', 0)
c.FlagSet.VisitAll(func(f *flag.Flag) {
space := " "
if isBoolFlag(f) {
space = "="
}

def := f.DefValue
if def == "" {
def = "..."
}
fmt.Fprintf(tw, " -%s %s\t%s\n", f.Name, def, f.Usage)

fmt.Fprintf(tw, " -%s%s%s\t%s\n", f.Name, space, def, f.Usage)
})
tw.Flush()
fmt.Fprintf(&b, "\n")
}

return strings.TrimSpace(b.String())
return strings.TrimSpace(b.String()) + "\n"
}

func countFlags(fs *flag.FlagSet) (n int) {
fs.VisitAll(func(*flag.Flag) { n++ })
return n
}

func isBoolFlag(f *flag.Flag) bool {
b, ok := f.Value.(interface {
IsBoolFlag() bool
})
return ok && b.IsBoolFlag()
}
10 changes: 5 additions & 5 deletions ffcli/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func TestHelpUsage(t *testing.T) {

err := command.ParseAndRun(context.Background(), testcase.args)
assertErrorIs(t, flag.ErrHelp, err)
assertString(t, testcase.output, buf.String())
assertMultilineString(t, testcase.output, buf.String())
})
}
}
Expand Down Expand Up @@ -512,10 +512,10 @@ func assertErrorIs(t *testing.T, want, have error) {
}
}

func assertString(t *testing.T, want, have string) {
func assertMultilineString(t *testing.T, want, have string) {
t.Helper()
if want != have {
t.Fatalf("want %q, have %q", want, have)
t.Fatalf("\nwant:\n%s\n\nhave:\n%s\n", want, have)
}
}

Expand Down Expand Up @@ -543,10 +543,10 @@ USAGE
Some long help.
FLAGS
-b false bool
-b=false bool
-d 0s time.Duration
-f 0 float64
-i 0 int
-s ... string
-x ... collection of strings (repeatable)
`) + "\n"
`) + "\n\n"

0 comments on commit 556df77

Please sign in to comment.