From 85f122153036c000c418197f901d1876e7c081fc Mon Sep 17 00:00:00 2001 From: Milas Bowman Date: Fri, 23 Sep 2022 11:31:57 -0400 Subject: [PATCH] env: fix errors on valid interpolation expressions The parser was too strict here and would reject valid constructs that used an unescaped `$` that was not part of a variable expression (and not ambiguous). Now, only errors for unmatched braced expressions (e.g. `${FOO`) are returned, but other valid cases are ignored and the `$` will be treated literally, e.g. `a $ string` -> `a $ string`, which is the same as in POSIX. Signed-off-by: Milas Bowman --- template/template.go | 2 +- template/template_test.go | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/template/template.go b/template/template.go index 7056a13a..27f7067a 100644 --- a/template/template.go +++ b/template/template.go @@ -31,7 +31,7 @@ var substitutionNamed = "[_a-z][_a-z0-9]*" var substitutionBraced = "[_a-z][_a-z0-9]*(?::?[-+?](.*}|[^}]*))?" var patternString = fmt.Sprintf( - "%s(?i:(?P%s)|(?P%s)|{(?P%s)}|(?P))", + "%s(?i:(?P%s)|(?P%s)|{(?:(?P%s)}|(?P)))", delimiter, delimiter, substitutionNamed, substitutionBraced, ) diff --git a/template/template_test.go b/template/template_test.go index a2a04441..27c0f0e4 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -47,10 +47,24 @@ func TestSubstituteNoMatch(t *testing.T) { assert.Equal(t, "foo", result) } +func TestUnescaped(t *testing.T) { + templates := []string{ + "a $ string", + "^REGEX$", + "$}", + "$", + } + + for _, expected := range templates { + actual, err := Substitute(expected, defaultMapping) + assert.NilError(t, err) + assert.Equal(t, expected, actual) + } +} + func TestInvalid(t *testing.T) { invalidTemplates := []string{ "${", - "$}", "${}", "${ }", "${ foo}",