Skip to content

Commit a0318cd

Browse files
committed
fix: Only strip the first "." from the path passed to deepGet
This makes it possible to use the empty string as a map key.
1 parent e0d71f8 commit a0318cd

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

internal/template/reflect.go

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,6 @@ import (
66
"strings"
77
)
88

9-
func stripPrefix(s, prefix string) string {
10-
path := s
11-
for {
12-
if strings.HasPrefix(path, ".") {
13-
path = path[1:]
14-
continue
15-
}
16-
break
17-
}
18-
return path
19-
}
20-
219
func deepGetImpl(v reflect.Value, path []string) interface{} {
2210
if !v.IsValid() {
2311
log.Printf("invalid value\n")
@@ -40,7 +28,7 @@ func deepGetImpl(v reflect.Value, path []string) interface{} {
4028
func deepGet(item interface{}, path string) interface{} {
4129
var parts []string
4230
if path != "" {
43-
parts = strings.Split(stripPrefix(path, "."), ".")
31+
parts = strings.Split(strings.TrimPrefix(path, "."), ".")
4432
}
4533
return deepGetImpl(reflect.ValueOf(item), parts)
4634
}

internal/template/reflect_test.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func TestDeepGetSimpleDotPrefix(t *testing.T) {
3434
item := context.RuntimeContainer{
3535
ID: "expected",
3636
}
37-
value := deepGet(item, "...ID")
37+
value := deepGet(item, ".ID")
3838
assert.IsType(t, "", value)
3939

4040
assert.Equal(t, "expected", value)
@@ -51,3 +51,31 @@ func TestDeepGetMap(t *testing.T) {
5151

5252
assert.Equal(t, "value", value)
5353
}
54+
55+
func TestDeepGet(t *testing.T) {
56+
for _, tc := range []struct {
57+
desc string
58+
item interface{}
59+
path string
60+
want interface{}
61+
}{
62+
{
63+
"map key empty string",
64+
map[string]map[string]map[string]string{
65+
"": map[string]map[string]string{
66+
"": map[string]string{
67+
"": "foo",
68+
},
69+
},
70+
},
71+
"...",
72+
"foo",
73+
},
74+
} {
75+
t.Run(tc.desc, func(t *testing.T) {
76+
got := deepGet(tc.item, tc.path)
77+
assert.IsType(t, tc.want, got)
78+
assert.Equal(t, tc.want, got)
79+
})
80+
}
81+
}

0 commit comments

Comments
 (0)