Add SubSlice to return slice of sub vipers

This commit is contained in:
andig 2020-03-08 18:27:23 +01:00
parent 97ee7adfef
commit deb8393798
2 changed files with 46 additions and 0 deletions

View file

@ -787,6 +787,28 @@ func (v *Viper) Sub(key string) *Viper {
return nil
}
// SubSlice returns a slice of new Viper instances representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func SubSlice(key string) []*Viper { return v.SubSlice(key) }
func (v *Viper) SubSlice(key string) []*Viper {
data := v.Get(key)
if data == nil {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Slice {
var vList []*Viper
for _, item := range data.([]interface{}) {
subv := New()
subv.config = cast.ToStringMap(item)
vList = append(vList, subv)
}
return vList
}
return nil
}
// GetString returns the value associated with the key as a string.
func GetString(key string) string { return v.GetString(key) }
func (v *Viper) GetString(key string) string {

View file

@ -1253,6 +1253,30 @@ func TestSub(t *testing.T) {
assert.Equal(t, (*Viper)(nil), subv)
}
func TestSubSlice(t *testing.T) {
var yamlList = []byte(`map:
foo: bar
list:
- foo: 0
bar: 0
- foo: 1
bar: 1
`)
v := New()
v.SetConfigType("yaml")
v.ReadConfig(bytes.NewBuffer(yamlList))
subvSlice := v.SubSlice("list")
for idx, subv := range subvSlice {
assert.Equal(t, subv.GetInt("foo"), idx)
assert.Equal(t, subv.GetInt("bar"), idx)
}
subvSlice = v.SubSlice("map")
assert.Equal(t, ([]*Viper)(nil), subvSlice)
}
var hclWriteExpected = []byte(`"foos" = {
"foo" = {
"key" = 1