Skip to content

Commit

Permalink
Fix usage showing zero defaults for custom Value type
Browse files Browse the repository at this point in the history
The defaultIsZeroValue() method was erroneously assuming that all types that implement IsBoolFlag() were bools - regardless of the return value of IsBoolFlag().

Fixes spf13#360
  • Loading branch information
twelvelabs committed Sep 22, 2022
1 parent d5e0c06 commit fdc249a
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
5 changes: 3 additions & 2 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -536,9 +536,10 @@ func (f *FlagSet) PrintDefaults() {
// defaultIsZeroValue returns true if the default value for this flag represents
// a zero value.
func (f *Flag) defaultIsZeroValue() bool {
switch f.Value.(type) {
case boolFlag:
if bf, ok := f.Value.(boolFlag); ok && bf.IsBoolFlag() {
return f.DefValue == "false"
}
switch f.Value.(type) {
case *durationValue:
// Beginning in Go 1.7, duration zero values are "0s"
return f.DefValue == "0" || f.DefValue == "0s"
Expand Down
6 changes: 3 additions & 3 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,6 @@ func TestMultipleNormalizeFlagNameInvocations(t *testing.T) {
}
}

//
func TestHiddenFlagInUsage(t *testing.T) {
f := NewFlagSet("bob", ContinueOnError)
f.Bool("secretFlag", true, "shhh")
Expand All @@ -1149,7 +1148,6 @@ func TestHiddenFlagInUsage(t *testing.T) {
}
}

//
func TestHiddenFlagUsage(t *testing.T) {
f := NewFlagSet("bob", ContinueOnError)
f.Bool("secretFlag", true, "shhh")
Expand Down Expand Up @@ -1202,6 +1200,8 @@ func (cv *customValue) Set(s string) error {

func (cv *customValue) Type() string { return "custom" }

func (cv *customValue) IsBoolFlag() bool { return false }

func TestPrintDefaults(t *testing.T) {
fs := NewFlagSet("print defaults test", ContinueOnError)
var buf bytes.Buffer
Expand Down Expand Up @@ -1239,7 +1239,7 @@ func TestPrintDefaults(t *testing.T) {
got := buf.String()
if got != defaultOutput {
fmt.Println("\n" + got)
fmt.Println("\n" + defaultOutput)
fmt.Print("\n" + defaultOutput)
t.Errorf("got %q want %q\n", got, defaultOutput)
}
}
Expand Down

0 comments on commit fdc249a

Please sign in to comment.