diff --git a/commands_test.go b/commands_test.go index 2e4924a4..d88d73a9 100644 --- a/commands_test.go +++ b/commands_test.go @@ -775,7 +775,7 @@ func TestWriteCmd_AppendEmptyArray(t *testing.T) { defer removeTempYamlFile(filename) cmd := getRootCommand() - result := runCmd(cmd, fmt.Sprintf("write %s b[+] v", filename)) + result := runCmd(cmd, fmt.Sprintf("write -v %s b[+] v", filename)) if result.Error != nil { t.Error(result.Error) } diff --git a/data_navigator.go b/data_navigator.go index d6f40087..39f03958 100644 --- a/data_navigator.go +++ b/data_navigator.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "reflect" "strconv" yaml "gopkg.in/mikefarah/yaml.v2" @@ -41,7 +42,7 @@ func getArray(context interface{}) (array []interface{}, ok bool) { } func writeMap(context interface{}, paths []string, value interface{}) yaml.MapSlice { - log.Debugf("writeMap for %v for %v with value %v\n", paths, context, value) + log.Debugf("writeMap with path %v for %v to set value %v\n", paths, context, value) mapSlice := getMapSlice(context) @@ -69,19 +70,25 @@ func updatedChildValue(child interface{}, remainingPaths []string, value interfa if len(remainingPaths) == 0 { return value } - + log.Debugf("updatedChildValue for child %v with path %v to set value %v", child, remainingPaths, value) + log.Debugf("type of child is %v", reflect.TypeOf(child)) _, nextIndexErr := strconv.ParseInt(remainingPaths[0], 10, 64) - if nextIndexErr != nil && remainingPaths[0] != "+" { - // must be a map - return writeMap(child, remainingPaths, value) - } - // must be an array - return writeArray(child, remainingPaths, value) + switch child := child.(type) { + case nil: + if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*" + return writeArray(child, remainingPaths, value) + } + case []interface{}: + if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*" + return writeArray(child, remainingPaths, value) + } + } + return writeMap(child, remainingPaths, value) } func writeArray(context interface{}, paths []string, value interface{}) []interface{} { - log.Debugf("writeArray for %v for %v with value %v\n", paths, context, value) + log.Debugf("writeArray with path %v for %v to set value %v\n", paths, context, value) array, _ := getArray(context) if len(paths) == 0 { diff --git a/data_navigator_test.go b/data_navigator_test.go index d592d352..fd41937f 100644 --- a/data_navigator_test.go +++ b/data_navigator_test.go @@ -253,11 +253,11 @@ b: func TestWrite_new_array_deep(t *testing.T) { var data = parseData(` -b: - c: 2 +a: apple `) - var expected = `b: + var expected = `a: apple +b: - c: "4"` updated := writeMap(data, []string{"b", "0", "c"}, "4")