From fcb2a1234c681a91dff4553f9bc21b929ac91513 Mon Sep 17 00:00:00 2001 From: Anton Voskresenskiy Date: Sat, 8 Feb 2020 14:30:44 -0800 Subject: [PATCH] custom flag usage string shoudln't change its 'default' section after parsing --- flag.go | 2 +- flag_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/flag.go b/flag.go index 24a5036e..5fe5141f 100644 --- a/flag.go +++ b/flag.go @@ -544,7 +544,7 @@ func (f *Flag) defaultIsZeroValue() bool { case *intSliceValue, *stringSliceValue, *stringArrayValue: return f.DefValue == "[]" default: - switch f.Value.String() { + switch f.DefValue { case "false": return true case "": diff --git a/flag_test.go b/flag_test.go index 7d02dbc8..e423fbbb 100644 --- a/flag_test.go +++ b/flag_test.go @@ -1262,3 +1262,39 @@ func TestVisitFlagOrder(t *testing.T) { i++ }) } + +// TestCustomFlagValue verifies that custom flag usage string doesn't change its "default" section after parsing +func TestCustomFlagDefValue(t *testing.T) { + fs := NewFlagSet("TestCustomFlagDefValue", ContinueOnError) + var buf bytes.Buffer + fs.SetOutput(&buf) + + var cv customValue + fs.VarP(&cv, "customP", "", "a VarP with no default") + + fs.PrintDefaults() + beforeParse := buf.String() + buf.Reset() + + args := []string{ + "--customP=10", + } + + if err := fs.Parse(args); err != nil { + t.Error("expected no error, got ", err) + } + + val := fs.Lookup("customP").Value.String() + if val != "10" { + t.Errorf("expected customP to be set to the new value, got %s\n", val) + } + + fs.PrintDefaults() + afterParse := buf.String() + + if beforeParse != afterParse { + fmt.Println("\n" + beforeParse) + fmt.Println("\n" + afterParse) + t.Errorf("got %q want %q\n", afterParse, beforeParse) + } +}