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

Support root level map keys in map sources #2047

Merged
merged 1 commit into from
Feb 8, 2025
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
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
Loading