From 32b2f740c921ebddcf8abe1a9f3ce781c25c93c2 Mon Sep 17 00:00:00 2001 From: Alec Thomas Date: Sat, 4 Dec 2021 21:06:09 +1100 Subject: [PATCH] Support $$ for escaping $ in interpolated values. Fixes #248 --- interpolate.go | 10 ++++++---- interpolate_test.go | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/interpolate.go b/interpolate.go index 8c6f742..dceeed0 100644 --- a/interpolate.go +++ b/interpolate.go @@ -5,7 +5,7 @@ import ( "regexp" ) -var interpolationRegex = regexp.MustCompile(`((?:\${([[:alpha:]_][[:word:]]*))(?:=([^}]+))?})|(\$)|([^$]+)`) +var interpolationRegex = regexp.MustCompile(`(\$\$)|((?:\${([[:alpha:]_][[:word:]]*))(?:=([^}]+))?})|(\$)|([^$]+)`) // Interpolate variables from vars into s for substrings in the form ${var} or ${var=default}. func interpolate(s string, vars Vars, updatedVars map[string]string) (string, error) { @@ -21,14 +21,16 @@ func interpolate(s string, vars Vars, updatedVars map[string]string) (string, er } } for _, match := range matches { - if name := match[2]; name != "" { + if dollar := match[1]; dollar != "" { + out += "$" + } else if name := match[3]; name != "" { value, ok := vars[name] if !ok { // No default value. - if match[3] == "" { + if match[4] == "" { return "", fmt.Errorf("undefined variable ${%s}", name) } - value = match[3] + value = match[4] } out += value } else { diff --git a/interpolate_test.go b/interpolate_test.go index 38d9266..399d114 100644 --- a/interpolate_test.go +++ b/interpolate_test.go @@ -13,7 +13,7 @@ func TestInterpolate(t *testing.T) { updatedVars := map[string]string{ "height": "180", } - actual, err := interpolate("${name=Bobby Brown} is ${age} years old and ${height} cm tall", vars, updatedVars) + actual, err := interpolate("${name=Bobby Brown} is ${age} years old and ${height} cm tall and likes $${AUD}", vars, updatedVars) require.NoError(t, err) - require.Equal(t, `Bobby Brown is 35 years old and 180 cm tall`, actual) + require.Equal(t, `Bobby Brown is 35 years old and 180 cm tall and likes ${AUD}`, actual) }