Skip to content

Commit

Permalink
fix: merge missing struct keys inside UnmarshalExact
Browse files Browse the repository at this point in the history
  • Loading branch information
krakowski authored and sagikazarmark committed Dec 8, 2023
1 parent f5fcb4a commit fb6eb1e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit fb6eb1e

Please sign in to comment.