From 53289366a597e16a0c76103019228cd0bb3596f5 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Wed, 1 May 2019 08:49:50 +1000 Subject: [PATCH] Write array splat --- commands_test.go | 20 ++++++++++++++++++++ data_navigator.go | 13 +++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/commands_test.go b/commands_test.go index d88d73a9..6f682abc 100644 --- a/commands_test.go +++ b/commands_test.go @@ -786,6 +786,26 @@ b: assertResult(t, expectedOutput, result.Output) } +func TestWriteCmd_SplatArray(t *testing.T) { + content := `b: +- c: thing +- c: another thing +` + filename := writeTempYamlFile(content) + defer removeTempYamlFile(filename) + + cmd := getRootCommand() + result := runCmd(cmd, fmt.Sprintf("write -v %s b[*].c new", filename)) + if result.Error != nil { + t.Error(result.Error) + } + expectedOutput := `b: +- c: new +- c: new +` + assertResult(t, expectedOutput, result.Output) +} + func TestDeleteYaml(t *testing.T) { content := `a: 2 b: diff --git a/data_navigator.go b/data_navigator.go index 39f03958..cb520dd5 100644 --- a/data_navigator.go +++ b/data_navigator.go @@ -73,14 +73,14 @@ func updatedChildValue(child interface{}, remainingPaths []string, value interfa 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) - + arrayCommand := nextIndexErr == nil || remainingPaths[0] == "+" || remainingPaths[0] == "*" switch child := child.(type) { case nil: - if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*" + if arrayCommand { return writeArray(child, remainingPaths, value) } case []interface{}: - if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*" + if arrayCommand { return writeArray(child, remainingPaths, value) } } @@ -98,10 +98,16 @@ func writeArray(context interface{}, paths []string, value interface{}) []interf log.Debugf("\tarray %v\n", array) rawIndex := paths[0] + remainingPaths := paths[1:] var index int64 // the append array indicator if rawIndex == "+" { index = int64(len(array)) + } else if rawIndex == "*" { + for index, oldChild := range array { + array[index] = updatedChildValue(oldChild, remainingPaths, value) + } + return array } else { index, _ = strconv.ParseInt(rawIndex, 10, 64) // nolint // writeArray is only called by updatedChildValue which handles parsing the @@ -115,7 +121,6 @@ func writeArray(context interface{}, paths []string, value interface{}) []interf log.Debugf("\tcurrentChild %v\n", currentChild) - remainingPaths := paths[1:] array[index] = updatedChildValue(currentChild, remainingPaths, value) log.Debugf("\tReturning array %v\n", array) return array