Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions flag_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,19 +366,18 @@ func (fs *flagSet) apply(envVars map[string]string, args []string) error {
// By definition, for the same name - all flags have the same "HasValue" value, so it should be safe to just
// take it from the first one
if mfd.HasValue {

// Set the field's default value so it's marked as "applied" (and thus the "required" validation will ignore it)
if mfd.DefaultValue != "" {
if err := mfd.setValue(mfd.DefaultValue); err != nil {
return fmt.Errorf("failed applying default value for flag '%s': %w", mfd.Name, err)
}
}
stdFs.Func(mfd.Name, "", func(v string) error { return mfd.setValue(v) })

} else {
stdFs.BoolFunc(mfd.Name, "", func(string) error { return mfd.setValue("true") })
}

// Set the field's default value so it's marked as "applied" (and thus the "required" validation will ignore it)
if mfd.DefaultValue != "" {
if err := mfd.setValue(mfd.DefaultValue); err != nil {
return fmt.Errorf("failed applying default value for flag '%s': %w", mfd.Name, err)
}
}

// Set the value to the flag's corresponding environment variable, if one was given
// Important this is done here, so it overrides the default value set earlier
if v, found := envVars[*mfd.EnvVarName]; found {
Expand Down
20 changes: 20 additions & 0 deletions flag_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,26 @@ func TestFlagSetApply(t *testing.T) {
args: []string{"--my-field1=VVV1"},
expectedError: `^required flag is missing: --my-field2$`,
},
"bool flag default value is considered": {
config: &struct {
F1 bool `name:"my-field1" required:"true"`
}{F1: false},
envVars: map[string]string{},
args: []string{},
expectedConfig: &struct {
F1 bool `name:"my-field1" required:"true"`
}{F1: false},
},
"bool flag default value overridden by arg": {
config: &struct {
F1 bool `name:"my-field1" required:"true"`
}{F1: false},
envVars: map[string]string{},
args: []string{"--my-field1"},
expectedConfig: &struct {
F1 bool `name:"my-field1" required:"true"`
}{F1: true},
},
}
for name, tc := range testCases {
tc := tc
Expand Down