From 2a9417d842317d21d6d9971f46adfa3d511db511 Mon Sep 17 00:00:00 2001 From: k1LoW Date: Fri, 8 Mar 2024 17:24:22 +0900 Subject: [PATCH] Fix --- expand_test.go | 35 ++++++++++++++++++++++++++++++++++- repfn.go | 11 +++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/expand_test.go b/expand_test.go index 8e201a5..8becab5 100644 --- a/expand_test.go +++ b/expand_test.go @@ -469,7 +469,7 @@ func TestReplaceYAMLWithExprRepFn(t *testing.T) { { map[string]any{ "hello": map[string]any{ - "foo": "ba\nr", + "foo": "bar", }, }, false, @@ -488,6 +488,39 @@ func TestReplaceYAMLWithExprRepFn(t *testing.T) { `v: '\{\{ {{ hello }} \}\}'`, `v: '{{ {"foo":"bar"} }}'`, }, + { + map[string]any{ + "hello": map[string]any{ + "foo": "bar", + }, + }, + false, + true, + `v: '\\{\{ hello \\}\}'`, + `v: '\{\{ hello \}\}'`, + }, + { + map[string]any{ + "hello": map[string]any{ + "foo": "bar", + }, + }, + false, + true, + `v: '\\\{\{ hello \\\}\}'`, + `v: '\\{\{ hello \\}\}'`, + }, + { + map[string]any{ + "hello": map[string]any{ + "foo": "bar", + }, + }, + false, + true, + `v: '\\{\\{ hello \\}\\}'`, + `v: '\\{\\{ hello \\}\\}'`, + }, } for i, tt := range tests { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { diff --git a/repfn.go b/repfn.go index 132decf..9193acc 100644 --- a/repfn.go +++ b/repfn.go @@ -137,6 +137,10 @@ func trySubstr(delimStart, delimEnd, in string) ([]string, int) { } func unescapeDelims(delimStart, delimEnd, in string) string { + const ( + eeStartToken = "__E_E_DELIM_START__" + eeEndToken = "__E_E_DELIM_END__" + ) var ( escapedDelimStart string escapedDelimEnd string @@ -144,9 +148,12 @@ func unescapeDelims(delimStart, delimEnd, in string) string { for _, r := range delimStart { escapedDelimStart += fmt.Sprintf("\\%s", string(r)) } + escapedescapedDelimStart := fmt.Sprintf("\\%s", escapedDelimStart) for _, r := range delimEnd { escapedDelimEnd += fmt.Sprintf("\\%s", string(r)) } - rep := strings.NewReplacer(escapedDelimStart, delimStart, escapedDelimEnd, delimEnd) - return rep.Replace(in) + escapedescapedDelimEnd := fmt.Sprintf("\\%s", escapedDelimEnd) + rep := strings.NewReplacer(escapedescapedDelimStart, eeStartToken, escapedescapedDelimEnd, eeEndToken, escapedDelimStart, delimStart, escapedDelimEnd, delimEnd) + rep2 := strings.NewReplacer(eeStartToken, escapedDelimStart, eeEndToken, escapedDelimEnd) + return rep2.Replace(rep.Replace(in)) }