Skip to content

Commit

Permalink
FIx SetDefaults for poitner to boolean with true as default value
Browse files Browse the repository at this point in the history
Tests were inaccurate. The default value was always set for pointers to bool
  • Loading branch information
upils committed Oct 20, 2023
1 parent 8b2b0fa commit 50d3a9e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
10 changes: 6 additions & 4 deletions internal/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,16 @@ func SetDefaults(needsDefaults interface{}) error {
}
// special case for pointer to bools
} else if field.Type().Elem() == reflect.TypeOf(true) {
// make sure the pointer is never nil in case no value
// was set
if field.IsNil() {
field.Set(reflect.ValueOf(BoolPtr(false)))
// if a value is set, do nothing
if !field.IsNil() {
continue
}
tags := elem.Type().Field(i).Tag
defaultValue, hasDefault := tags.Lookup("default")
if !hasDefault {
// If no default and no value is set, make sure we have a valid
// value consistent with the "zero" value for a bool (false)
field.Set(reflect.ValueOf(BoolPtr(false)))
continue
}
if defaultValue == "true" {
Expand Down
2 changes: 1 addition & 1 deletion internal/helper/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ func TestSetDefaults(t *testing.T) {
},
want: &S2{
A: "test",
B: BoolPtr(true),
B: BoolPtr(false),
C: BoolPtr(false),
D: BoolPtr(true),
},
Expand Down

0 comments on commit 50d3a9e

Please sign in to comment.