yq/data_navigator.go

69 lines
1.6 KiB
Go
Raw Normal View History

2015-10-01 23:05:13 +00:00
package main
import (
2015-10-03 05:10:29 +00:00
// "fmt"
2015-10-01 23:05:13 +00:00
"log"
"strconv"
)
func write(context map[interface{}]interface{}, head string, tail []string, value interface{}) {
// e.g. if updating a.b.c, we need to get the 'b' map...
toUpdate := readMap(context, head, tail[0:len(tail)-1]).(map[interface{}]interface{})
// and then set the 'c' key.
key := (tail[len(tail)-1])
toUpdate[key] = value
}
func readMap(context map[interface{}]interface{}, head string, tail []string) interface{} {
value := context[head]
if len(tail) > 0 {
return recurse(value, tail[0], tail[1:len(tail)])
}
return value
}
func recurse(value interface{}, head string, tail []string) interface{} {
switch value.(type) {
case []interface{}:
2015-10-05 03:41:01 +00:00
if head == "*" {
return readArraySplat(value.([]interface{}), tail)
}
2015-10-01 23:05:13 +00:00
index, err := strconv.ParseInt(head, 10, 64)
if err != nil {
log.Fatalf("Error accessing array: %v", err)
}
return readArray(value.([]interface{}), index, tail)
2015-10-03 07:06:33 +00:00
case nil:
return nil
2015-10-01 23:05:13 +00:00
default:
return readMap(value.(map[interface{}]interface{}), head, tail)
}
}
func readArray(array []interface{}, head int64, tail []string) interface{} {
if head > int64(len(array)) {
return nil
}
2015-10-01 23:05:13 +00:00
value := array[head]
if len(tail) > 0 {
return recurse(value, tail[0], tail[1:len(tail)])
}
return value
}
2015-10-05 03:41:01 +00:00
func readArraySplat(array []interface{}, tail []string) interface{} {
var newArray = make([]interface{}, len(array))
for index, value := range array {
newArray[index] = calculateValue(value, tail)
}
return newArray
}
func calculateValue(value interface{}, tail []string) interface{} {
if len(tail) > 0 {
return recurse(value, tail[0], tail[1:len(tail)])
}
return value
}