Skip to content

Commit a57d889

Browse files
authored
fix: improve handling of empty default boolean values in config binding (#258)
1 parent 058bfb0 commit a57d889

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

config/config.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,15 @@ func traverseStruct(value reflect.Value, flagSet *pflag.FlagSet, prefix string)
157157
flagSet.Int(prefix+tag, i, description)
158158
}
159159
case reflect.Bool:
160-
b, err := strconv.ParseBool(defaultStrValue)
161-
if err != nil {
162-
return err
160+
var defaultBoolValue bool
161+
if defaultStrValue != "" {
162+
b, err := strconv.ParseBool(defaultStrValue)
163+
if err != nil {
164+
return err
165+
}
166+
defaultBoolValue = b
163167
}
164-
flagSet.Bool(prefix+tag, b, description)
168+
flagSet.Bool(prefix+tag, defaultBoolValue, description)
165169
default:
166170
return fmt.Errorf("unsupported field type %s for field %s", fieldValue.Kind(), field.Name)
167171
}

config/config_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,25 @@ func TestBindConfigToFlagsWrongTypeBool(t *testing.T) {
118118
assert.Error(t, err)
119119
}
120120

121+
func TestBindConfigToFlagsEmptyDefaultBool(t *testing.T) {
122+
type test struct {
123+
CustomFlagInt bool `mapstructure:"custom-flag" default:""`
124+
}
125+
126+
testStruct := test{}
127+
128+
v := viper.New()
129+
130+
cmd := &cobra.Command{}
131+
err := config.BindConfigToFlags(v, cmd, &testStruct) // assuming this binds flags
132+
assert.NoError(t, err)
133+
134+
boolFlag := cmd.Flags().Lookup("custom-flag")
135+
assert.NotNil(t, boolFlag)
136+
assert.Equal(t, "Set the custom-flag", boolFlag.Usage)
137+
assert.Equal(t, "false", boolFlag.DefValue)
138+
}
139+
121140
func TestBindConfigToFlagsWrongType(t *testing.T) {
122141
type test struct {
123142
CustomFlagInt byte `mapstructure:"custom-flag" default:"abc"`

0 commit comments

Comments
 (0)