From 84de9c078dd9f52a50182c79c96e63a21ff1756e Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Thu, 16 May 2019 10:01:34 +1000 Subject: [PATCH] Improved handling of numeric keys When there is no match at a given path, numeric keys are assumed to be strings. To create an array '+' must be used. e.g: yq n thing[+].cat fred will create an array under thing, whereas yq n thing[0].cat fred will create a map under thing, with a key '0' --- commands_test.go | 3 +-- data_navigator.go | 7 ++++--- data_navigator_test.go | 4 ++-- examples/instruction_sample.yaml | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/commands_test.go b/commands_test.go index d74fff56..469068b4 100644 --- a/commands_test.go +++ b/commands_test.go @@ -385,12 +385,11 @@ func TestPrefixCmdArray(t *testing.T) { defer removeTempYamlFile(filename) cmd := getRootCommand() - result := runCmd(cmd, fmt.Sprintf("prefix %s [0].d.[1]", filename)) + result := runCmd(cmd, fmt.Sprintf("prefix %s [+].d.[+]", filename)) if result.Error != nil { t.Error(result.Error) } expectedOutput := `- d: - - null - b: c: 3 ` diff --git a/data_navigator.go b/data_navigator.go index c44a2b07..79157dd4 100644 --- a/data_navigator.go +++ b/data_navigator.go @@ -89,14 +89,15 @@ 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 arrayCommand { + if remainingPaths[0] == "+" || remainingPaths[0] == "*" { return writeArray(child, remainingPaths, value) } case []interface{}: + _, nextIndexErr := strconv.ParseInt(remainingPaths[0], 10, 64) + arrayCommand := nextIndexErr == nil || remainingPaths[0] == "+" || remainingPaths[0] == "*" if arrayCommand { return writeArray(child, remainingPaths, value) } diff --git a/data_navigator_test.go b/data_navigator_test.go index 03e50a33..206346ff 100644 --- a/data_navigator_test.go +++ b/data_navigator_test.go @@ -260,7 +260,7 @@ a: apple b: - c: "4"` - updated := writeMap(data, []string{"b", "0", "c"}, "4") + updated := writeMap(data, []string{"b", "+", "c"}, "4") got, _ := yamlToString(updated) assertResult(t, expected, got) } @@ -275,7 +275,7 @@ b: d: - "4"` - updated := writeMap(data, []string{"b", "d", "0"}, "4") + updated := writeMap(data, []string{"b", "d", "+"}, "4") got, _ := yamlToString(updated) assertResult(t, expected, got) } diff --git a/examples/instruction_sample.yaml b/examples/instruction_sample.yaml index 1250a747..ee2f8e8d 100644 --- a/examples/instruction_sample.yaml +++ b/examples/instruction_sample.yaml @@ -1,2 +1,2 @@ b.c: cat -b.e[0].name: Mike Farah +b.e[+].name: Mike Farah