+6
-4
@@ -5,7 +5,7 @@ import (
|
|||||||
"regexp"
|
"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}.
|
// 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) {
|
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 {
|
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]
|
value, ok := vars[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
// No default value.
|
// No default value.
|
||||||
if match[3] == "" {
|
if match[4] == "" {
|
||||||
return "", fmt.Errorf("undefined variable ${%s}", name)
|
return "", fmt.Errorf("undefined variable ${%s}", name)
|
||||||
}
|
}
|
||||||
value = match[3]
|
value = match[4]
|
||||||
}
|
}
|
||||||
out += value
|
out += value
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+2
-2
@@ -13,7 +13,7 @@ func TestInterpolate(t *testing.T) {
|
|||||||
updatedVars := map[string]string{
|
updatedVars := map[string]string{
|
||||||
"height": "180",
|
"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.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)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user