Skip to content

Commit e0d71f8

Browse files
committed
chore: Refactor deepGet
This will make it easier to fix bugs and add new features.
1 parent c7b991e commit e0d71f8

File tree

1 file changed

+21
-24
lines changed

1 file changed

+21
-24
lines changed

internal/template/reflect.go

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -18,32 +18,29 @@ func stripPrefix(s, prefix string) string {
1818
return path
1919
}
2020

21-
func deepGet(item interface{}, path string) interface{} {
22-
if path == "" {
23-
return item
21+
func deepGetImpl(v reflect.Value, path []string) interface{} {
22+
if !v.IsValid() {
23+
log.Printf("invalid value\n")
24+
return nil
2425
}
25-
26-
path = stripPrefix(path, ".")
27-
parts := strings.Split(path, ".")
28-
itemValue := reflect.ValueOf(item)
29-
30-
if len(parts) > 0 {
31-
switch itemValue.Kind() {
32-
case reflect.Struct:
33-
fieldValue := itemValue.FieldByName(parts[0])
34-
if fieldValue.IsValid() {
35-
return deepGet(fieldValue.Interface(), strings.Join(parts[1:], "."))
36-
}
37-
case reflect.Map:
38-
mapValue := itemValue.MapIndex(reflect.ValueOf(parts[0]))
39-
if mapValue.IsValid() {
40-
return deepGet(mapValue.Interface(), strings.Join(parts[1:], "."))
41-
}
42-
default:
43-
log.Printf("Can't group by %s (value %v, kind %s)\n", path, itemValue, itemValue.Kind())
44-
}
26+
if len(path) == 0 {
27+
return v.Interface()
28+
}
29+
switch v.Kind() {
30+
case reflect.Struct:
31+
return deepGetImpl(v.FieldByName(path[0]), path[1:])
32+
case reflect.Map:
33+
return deepGetImpl(v.MapIndex(reflect.ValueOf(path[0])), path[1:])
34+
default:
35+
log.Printf("unable to index by %s (value %v, kind %s)\n", path[0], v, v.Kind())
4536
return nil
4637
}
38+
}
4739

48-
return itemValue.Interface()
40+
func deepGet(item interface{}, path string) interface{} {
41+
var parts []string
42+
if path != "" {
43+
parts = strings.Split(stripPrefix(path, "."), ".")
44+
}
45+
return deepGetImpl(reflect.ValueOf(item), parts)
4946
}

0 commit comments

Comments
 (0)