Skip to content

Commit

Permalink
Merge pull request #2047 from lukasbindreiter/main
Browse files Browse the repository at this point in the history
Support root level map keys in map sources
  • Loading branch information
dearchap authored Feb 8, 2025
2 parents 435b91c + 0fe0a1c commit 8e49873
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
23 changes: 15 additions & 8 deletions value_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,19 @@ func (ms *mapSource) GoString() string {
return fmt.Sprintf("&mapSource{name:%[1]q}", ms.name)
}

// Lookup returns a value from the map source. The lookup name may be a dot-separated path into the map.
// If that is the case, it will recursively traverse the map based on the '.' delimited sections to find
// a nested value for the key.
func (ms *mapSource) Lookup(name string) (any, bool) {
// nestedVal checks if the name has '.' delimiters.
// If so, it tries to traverse the tree by the '.' delimited sections to find
// a nested value for the key.
if sections := strings.Split(name, "."); len(sections) > 1 {
node := ms.m
sections := strings.Split(name, ".")
if name == "" || len(sections) == 0 {
return nil, false
}

node := ms.m

// traverse into the map based on the dot-separated sections
if len(sections) >= 2 { // the last section is the value we want, we will return it directly at the end
for _, section := range sections[:len(sections)-1] {
child, ok := node[section]
if !ok {
Expand All @@ -213,11 +220,11 @@ func (ms *mapSource) Lookup(name string) (any, bool) {
return nil, false
}
}
if val, ok := node[sections[len(sections)-1]]; ok {
return val, true
}
}

if val, ok := node[sections[len(sections)-1]]; ok {
return val, true
}
return nil, false
}

Expand Down
18 changes: 18 additions & 0 deletions value_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ func TestMapValueSource(t *testing.T) {
"foo": 10,
},
},
{
name: "Level 1",
key: "foobar",
m: map[any]any{
"foobar": 10,
},
val: "10",
found: true,
},
{
name: "Level 2",
key: "foo.bar",
Expand All @@ -241,6 +250,15 @@ func TestMapValueSource(t *testing.T) {
},
},
},
{
name: "Level 2 string map type",
key: "foo.bar1",
m: map[any]any{
"foo": map[string]any{
"bar": "10",
},
},
},
{
name: "Level 3 no entry",
key: "foo.bar.t",
Expand Down

0 comments on commit 8e49873

Please sign in to comment.