forked from JoelLinn/docker-gen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reflect.go
49 lines (43 loc) · 984 Bytes
/
reflect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package dockergen
import (
"log"
"reflect"
"strings"
)
func stripPrefix(s, prefix string) string {
path := s
for {
if strings.HasPrefix(path, ".") {
path = path[1:]
continue
}
break
}
return path
}
func deepGet(item interface{}, path string) interface{} {
if path == "" {
return item
}
path = stripPrefix(path, ".")
parts := strings.Split(path, ".")
itemValue := reflect.ValueOf(item)
if len(parts) > 0 {
switch itemValue.Kind() {
case reflect.Struct:
fieldValue := itemValue.FieldByName(parts[0])
if fieldValue.IsValid() {
return deepGet(fieldValue.Interface(), strings.Join(parts[1:], "."))
}
case reflect.Map:
mapValue := itemValue.MapIndex(reflect.ValueOf(parts[0]))
if mapValue.IsValid() {
return deepGet(mapValue.Interface(), strings.Join(parts[1:], "."))
}
default:
log.Printf("Can't group by %s (value %v, kind %s)\n", path, itemValue, itemValue.Kind())
}
return nil
}
return itemValue.Interface()
}