Skip to content

Commit

Permalink
Use DefValue for usage
Browse files Browse the repository at this point in the history
Right now the "defaults" section of the usage line of a custom flag is
generated based on the value of "f.Value.String()" which can change
after parsing. So the "usage" info returned by the following two
types of invocation can be different:

(--customFlag has no default)
./program --help
./program --customFlag=10 --help

Merges spf13#243
  • Loading branch information
avoskresensky authored and hoshsadiq committed Feb 4, 2022
1 parent eae4d57 commit 2ef797a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,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 "<nil>":
Expand Down
36 changes: 36 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1494,3 +1494,39 @@ func TestUnquoteUsage(t *testing.T) {
}
buf.Reset()
}

// 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)
}
}

0 comments on commit 2ef797a

Please sign in to comment.