mirror of
https://github.com/spf13/viper
synced 2024-12-23 03:57:01 +00:00
Refactored IsSet to examine keys
This patch refactors the IsSet function to examine the keys in order to see if a key is set instead of simply checking if a value is nil. This change is necessary due to the fact that default values via flag bindings will result in the old logic always being true for the IsSet function due to a type's default value such as 0 for an integer or an empty string for a string. While a type's default value may be preferable when getting the value for a key, it results in a false positive when determining if a key is actually set. This change enables users to detect whether a key is set by only returning a flag's value if it has changed.
This commit is contained in:
parent
e37b56e207
commit
f9e7a97f3c
2 changed files with 26 additions and 2 deletions
17
viper.go
17
viper.go
|
@ -742,8 +742,21 @@ func (v *Viper) find(key string) interface{} {
|
||||||
// Check to see if the key has been set in any of the data locations
|
// Check to see if the key has been set in any of the data locations
|
||||||
func IsSet(key string) bool { return v.IsSet(key) }
|
func IsSet(key string) bool { return v.IsSet(key) }
|
||||||
func (v *Viper) IsSet(key string) bool {
|
func (v *Viper) IsSet(key string) bool {
|
||||||
t := v.Get(key)
|
path := strings.Split(key, v.keyDelim)
|
||||||
return t != nil
|
|
||||||
|
lcaseKey := strings.ToLower(key)
|
||||||
|
val := v.find(lcaseKey)
|
||||||
|
|
||||||
|
if val == nil {
|
||||||
|
source := v.find(strings.ToLower(path[0]))
|
||||||
|
if source != nil {
|
||||||
|
if reflect.TypeOf(source).Kind() == reflect.Map {
|
||||||
|
val = v.searchMap(cast.ToStringMap(source), path[1:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return val != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Have Viper check ENV variables for all
|
// Have Viper check ENV variables for all
|
||||||
|
|
|
@ -611,6 +611,17 @@ func TestReadBufConfig(t *testing.T) {
|
||||||
assert.Equal(t, 35, v.Get("age"))
|
assert.Equal(t, 35, v.Get("age"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIsSet(t *testing.T) {
|
||||||
|
v := New()
|
||||||
|
v.SetConfigType("yaml")
|
||||||
|
v.ReadConfig(bytes.NewBuffer(yamlExample))
|
||||||
|
assert.True(t, v.IsSet("clothing.jacket"))
|
||||||
|
assert.False(t, v.IsSet("clothing.jackets"))
|
||||||
|
assert.False(t, v.IsSet("helloworld"))
|
||||||
|
v.Set("helloworld", "fubar")
|
||||||
|
assert.True(t, v.IsSet("helloworld"))
|
||||||
|
}
|
||||||
|
|
||||||
func TestDirsSearch(t *testing.T) {
|
func TestDirsSearch(t *testing.T) {
|
||||||
|
|
||||||
root, config, cleanup := initDirs(t)
|
root, config, cleanup := initDirs(t)
|
||||||
|
|
Loading…
Reference in a new issue