From a46386e09370cc4b6106c61aeab44b2b2dd28722 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Tue, 18 Feb 2020 20:18:49 +1100 Subject: [PATCH] Fixed special characters in path for merging --- cmd/commands_test.go | 21 +++++++++++++++++++++ pkg/yqlib/lib.go | 17 ++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/cmd/commands_test.go b/cmd/commands_test.go index 8f4f8b62..78432460 100644 --- a/cmd/commands_test.go +++ b/cmd/commands_test.go @@ -1999,6 +1999,27 @@ apples: red test.AssertResult(t, expectedOutput, result.Output) } +func TestMergeSpecialCharacterKeysCmd(t *testing.T) { + content := `` + filename := test.WriteTempYamlFile(content) + defer test.RemoveTempYamlFile(filename) + + mergeContent := `key[bracket]: value +key.bracket: value +key"value": value +key'value': value +` + mergeFilename := test.WriteTempYamlFile(mergeContent) + defer test.RemoveTempYamlFile(mergeFilename) + + cmd := getRootCommand() + result := test.RunCmd(cmd, fmt.Sprintf("merge %s %s", filename, mergeFilename)) + if result.Error != nil { + t.Error(result.Error) + } + test.AssertResult(t, mergeContent, result.Output) +} + func TestMergeYamlMultiAllOverwriteCmd(t *testing.T) { content := `b: c: 3 diff --git a/pkg/yqlib/lib.go b/pkg/yqlib/lib.go index 0cba90df..89036291 100644 --- a/pkg/yqlib/lib.go +++ b/pkg/yqlib/lib.go @@ -71,13 +71,20 @@ func mergePathStackToString(pathStack []interface{}, appendArrays bool) string { s := fmt.Sprintf("%v", path) var _, errParsingInt = strconv.ParseInt(s, 10, 64) // nolint - hasDot := strings.Contains(s, ".") - if hasDot || errParsingInt == nil { - sb.WriteString("\"") + hasSpecial := strings.Contains(s, ".") || strings.Contains(s, "[") || strings.Contains(s, "]") || strings.Contains(s, "\"") + hasDoubleQuotes := strings.Contains(s, "\"") + wrappingCharacterStart := "\"" + wrappingCharacterEnd := "\"" + if hasDoubleQuotes { + wrappingCharacterStart = "(" + wrappingCharacterEnd = ")" + } + if hasSpecial || errParsingInt == nil { + sb.WriteString(wrappingCharacterStart) } sb.WriteString(s) - if hasDot || errParsingInt == nil { - sb.WriteString("\"") + if hasSpecial || errParsingInt == nil { + sb.WriteString(wrappingCharacterEnd) } }