Support for default values ${var=default} in interpolation variables.

This commit is contained in:
Alec Thomas
2019-09-24 13:33:20 +10:00
parent f7d3d9bfb5
commit 9a1f499155
3 changed files with 13 additions and 10 deletions
+8 -5
View File
@@ -5,18 +5,21 @@ 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}.
// Interpolate variables from vars into s for substrings in the form ${var} or ${var=default}.
func interpolate(s string, vars map[string]string) (string, error) {
out := ""
matches := interpolationRegex.FindAllStringSubmatch(s, -1)
for _, match := range matches {
if match[1] != "" {
name := match[1][2 : len(match[1])-1]
if name := match[2]; name != "" {
value, ok := vars[name]
if !ok {
return "", fmt.Errorf("undefined variable ${%s}", name)
// No default value.
if match[3] == "" {
return "", fmt.Errorf("undefined variable ${%s}", name)
}
value = match[3]
}
out += value
} else {