Fixed write bug: can now update yaml with single key in path

This commit is contained in:
mfarah 2015-10-05 15:59:59 +11:00
parent 8409be1cdf
commit 7db31006da
2 changed files with 17 additions and 5 deletions

View File

@ -7,12 +7,16 @@ import (
) )
func write(context map[interface{}]interface{}, head string, tail []string, value interface{}) { func write(context map[interface{}]interface{}, head string, tail []string, value interface{}) {
if len(tail) == 0 {
context[head] = value
} else {
// e.g. if updating a.b.c, we need to get the 'b' map... // 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{}) toUpdate := readMap(context, head, tail[0:len(tail)-1]).(map[interface{}]interface{})
// and then set the 'c' key. // and then set the 'c' key.
key := (tail[len(tail)-1]) key := (tail[len(tail)-1])
toUpdate[key] = value toUpdate[key] = value
} }
}
func readMap(context map[interface{}]interface{}, head string, tail []string) interface{} { func readMap(context map[interface{}]interface{}, head string, tail []string) interface{} {
value := context[head] value := context[head]

View File

@ -68,6 +68,14 @@ func TestWrite_simple(t *testing.T) {
assertResult(t, "4", b["c"].(string)) assertResult(t, "4", b["c"].(string))
} }
func TestWrite_with_no_tail(t *testing.T) {
write(parsedData, "b", []string{}, "4")
b := parsedData["b"]
assertResult(t, "4", fmt.Sprintf("%v", b))
}
func assertResult(t *testing.T, expectedValue interface{}, actualValue interface{}) { func assertResult(t *testing.T, expectedValue interface{}, actualValue interface{}) {
if expectedValue != actualValue { if expectedValue != actualValue {
t.Error("Expected <", expectedValue, "> but got <", actualValue, ">", fmt.Sprintf("%T", actualValue)) t.Error("Expected <", expectedValue, "> but got <", actualValue, ">", fmt.Sprintf("%T", actualValue))