tracker/stats/struct_flattener.go

102 lines
2 KiB
Go
Raw Normal View History

2014-07-25 01:35:15 +02:00
package stats
import (
"reflect"
"strings"
)
type FlatMap map[string]interface{}
func isEmptyValue(v reflect.Value) bool {
return v.Interface() == reflect.Zero(v.Type()).Interface()
}
2014-07-25 02:27:20 +02:00
func keyForField(field reflect.StructField, v reflect.Value) (string, bool) {
2014-07-25 01:35:15 +02:00
if tag := field.Tag.Get("json"); tag != "" {
tokens := strings.SplitN(tag, ",", 2)
name := tokens[0]
opts := ""
if len(tokens) > 1 {
opts = tokens[1]
}
if name == "-" || strings.Contains(opts, "omitempty") && isEmptyValue(v) {
2014-07-25 02:27:20 +02:00
return "", false
2014-07-25 01:35:15 +02:00
} else if name != "" {
2014-07-25 02:27:20 +02:00
return name, false
2014-07-25 01:35:15 +02:00
}
}
2014-07-25 02:27:20 +02:00
if field.Anonymous {
return "", true
}
return field.Name, false
}
func extractValue(val, fallback reflect.Value) reflect.Value {
switch val.Kind() {
case reflect.Struct:
return val
case reflect.Ptr:
return extractValue(val.Elem(), fallback)
case reflect.Interface:
return extractValue(val.Elem(), fallback)
default:
return fallback
}
2014-07-25 01:35:15 +02:00
}
func recursiveFlatten(val reflect.Value, prefix string, output FlatMap) int {
valType := val.Type()
added := 0
for i := 0; i < val.NumField(); i++ {
child := val.Field(i)
childType := valType.Field(i)
2014-07-25 02:27:20 +02:00
childPrefix := ""
key, anonymous := keyForField(childType, child)
2014-07-25 01:35:15 +02:00
2014-07-25 02:27:20 +02:00
if childType.PkgPath != "" || (key == "" && !anonymous) {
2014-07-25 01:35:15 +02:00
continue
2014-07-25 02:27:20 +02:00
}
child = extractValue(child, child)
if !anonymous {
childPrefix = prefix + key + "."
}
if child.Kind() == reflect.Struct {
childAdded := recursiveFlatten(child, childPrefix, output)
if childAdded != 0 {
added += childAdded
2014-07-25 01:35:15 +02:00
continue
}
}
2014-07-25 02:27:20 +02:00
output[prefix+key] = child.Addr().Interface()
2014-07-25 01:35:15 +02:00
added++
}
return added
}
func flattenPointer(val reflect.Value) FlatMap {
if val.Kind() == reflect.Ptr {
return flattenPointer(val.Elem())
}
if val.Kind() != reflect.Struct {
panic("must be called with a struct type")
}
m := FlatMap{}
recursiveFlatten(val, "", m)
return m
}
func Flatten(val interface{}) FlatMap {
return flattenPointer(reflect.ValueOf(val))
}