Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
45 changes: 45 additions & 0 deletions legacy_bool_help_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}