Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge missing struct keys inside UnmarshalExact #1704

Merged
merged 1 commit into from
Dec 8, 2023
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
9 changes: 8 additions & 1 deletion viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1179,7 +1179,14 @@ func (v *Viper) UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
config := defaultDecoderConfig(rawVal, opts...)
config.ErrorUnused = true

return decode(v.AllSettings(), config)
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}

// TODO: struct keys should be enough?
return decode(v.getSettings(append(v.AllKeys(), structKeys...)), config)
}

// BindPFlags binds a full flag set to the configuration, using each flag's long
Expand Down
26 changes: 26 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,32 @@ func TestUnmarshalWithAutomaticEnv(t *testing.T) {

assert.Error(t, err, "expected viper.Unmarshal to return error due to unset field 'FLAG'")
})

t.Run("Exact", func(t *testing.T) {
var config Configuration

v.Set("port", 1234)
if err := v.UnmarshalExact(&config); err != nil {
t.Fatalf("unable to decode into struct, %v", err)
}

assert.Equal(
t,
Configuration{
Name: "Steve",
Port: 1234,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
Authentication: AuthConfig{
Secret: "42",
},
Storage: StorageConfig{
Size: 4096,
},
},
config,
)
})
}

func TestBindPFlags(t *testing.T) {
Expand Down
Loading