Skip to content

Commit 0fe0a1c

Browse files
Support root level map keys in map sources
1 parent 435b91c commit 0fe0a1c

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

value_source.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,19 @@ func (ms *mapSource) GoString() string {
189189
return fmt.Sprintf("&mapSource{name:%[1]q}", ms.name)
190190
}
191191

192+
// Lookup returns a value from the map source. The lookup name may be a dot-separated path into the map.
193+
// If that is the case, it will recursively traverse the map based on the '.' delimited sections to find
194+
// a nested value for the key.
192195
func (ms *mapSource) Lookup(name string) (any, bool) {
193-
// nestedVal checks if the name has '.' delimiters.
194-
// If so, it tries to traverse the tree by the '.' delimited sections to find
195-
// a nested value for the key.
196-
if sections := strings.Split(name, "."); len(sections) > 1 {
197-
node := ms.m
196+
sections := strings.Split(name, ".")
197+
if name == "" || len(sections) == 0 {
198+
return nil, false
199+
}
200+
201+
node := ms.m
202+
203+
// traverse into the map based on the dot-separated sections
204+
if len(sections) >= 2 { // the last section is the value we want, we will return it directly at the end
198205
for _, section := range sections[:len(sections)-1] {
199206
child, ok := node[section]
200207
if !ok {
@@ -213,11 +220,11 @@ func (ms *mapSource) Lookup(name string) (any, bool) {
213220
return nil, false
214221
}
215222
}
216-
if val, ok := node[sections[len(sections)-1]]; ok {
217-
return val, true
218-
}
219223
}
220224

225+
if val, ok := node[sections[len(sections)-1]]; ok {
226+
return val, true
227+
}
221228
return nil, false
222229
}
223230

value_source_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,15 @@ func TestMapValueSource(t *testing.T) {
221221
"foo": 10,
222222
},
223223
},
224+
{
225+
name: "Level 1",
226+
key: "foobar",
227+
m: map[any]any{
228+
"foobar": 10,
229+
},
230+
val: "10",
231+
found: true,
232+
},
224233
{
225234
name: "Level 2",
226235
key: "foo.bar",
@@ -241,6 +250,15 @@ func TestMapValueSource(t *testing.T) {
241250
},
242251
},
243252
},
253+
{
254+
name: "Level 2 string map type",
255+
key: "foo.bar1",
256+
m: map[any]any{
257+
"foo": map[string]any{
258+
"bar": "10",
259+
},
260+
},
261+
},
244262
{
245263
name: "Level 3 no entry",
246264
key: "foo.bar.t",

0 commit comments

Comments
 (0)