diff --git a/flag.go b/flag.go index dc47fff2..0c4aba0e 100644 --- a/flag.go +++ b/flag.go @@ -163,6 +163,10 @@ type FlagSet struct { // help/usage messages. SortFlags bool + // LegacyBoolHelp restores pre-v1.0.6 bool flag help formatting by omitting + // the [=true|false] syntax hint and default value from help output. + LegacyBoolHelp bool + // ParseErrorsAllowlist is used to configure an allowlist of errors ParseErrorsAllowlist ParseErrorsAllowlist @@ -731,7 +735,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string { } varname, usage := UnquoteUsage(flag) - if flag.Value.Type() == "bool" { + if flag.Value.Type() == "bool" && !f.LegacyBoolHelp { line += "[=true|false]" } else if varname != "" { line += " " + varname @@ -762,7 +766,13 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string { } line += usage - if !flag.defaultIsZeroValue() { + hideDefault := flag.defaultIsZeroValue() + if f.LegacyBoolHelp { + if _, ok := flag.Value.(boolFlag); ok { + hideDefault = true + } + } + if !hideDefault { if flag.Value.Type() == "string" { line += fmt.Sprintf(" (default %q)", flag.DefValue) } else { diff --git a/legacy_bool_help_test.go b/legacy_bool_help_test.go new file mode 100644 index 00000000..8e4c88a3 --- /dev/null +++ b/legacy_bool_help_test.go @@ -0,0 +1,45 @@ +package pflag + +import ( + "bytes" + "strings" + "testing" +) + +func TestLegacyBoolHelp(t *testing.T) { + buf := bytes.Buffer{} + f := NewFlagSet("test", ContinueOnError) + f.LegacyBoolHelp = true + f.Bool("enabled", false, "Enable the feature") + f.Bool("verbose", true, "Verbose logging") + f.SetOutput(&buf) + f.PrintDefaults() + + got := buf.String() + if strings.Contains(got, "[=true|false]") { + t.Fatalf("legacy bool help should omit [=true|false], got:\n%s", got) + } + if strings.Contains(got, "(default true)") || strings.Contains(got, "(default false)") { + t.Fatalf("legacy bool help should omit bool defaults, got:\n%s", got) + } + if !strings.Contains(got, "Enable the feature") || !strings.Contains(got, "Verbose logging") { + t.Fatalf("expected usage text in output, got:\n%s", got) + } +} + +func TestLegacyBoolHelpBoolFunc(t *testing.T) { + buf := bytes.Buffer{} + f := NewFlagSet("test", ContinueOnError) + f.LegacyBoolHelp = true + f.BoolFunc("callback", "Run callback", func(string) error { return nil }) + f.SetOutput(&buf) + f.PrintDefaults() + + got := buf.String() + if strings.Contains(got, "(default ") { + t.Fatalf("legacy bool help should omit boolfunc defaults, got:\n%s", got) + } + if !strings.Contains(got, "Run callback") { + t.Fatalf("expected usage text in output, got:\n%s", got) + } +}