lib/envtemplate: allow non-env var names inside "%{ ... }"

This commit is contained in:
Aliaksandr Valialkin 2022-11-07 13:15:51 +02:00
parent dd88c628aa
commit 116811d761
No known key found for this signature in database
GPG key ID: A72BEC6CD3D0DED1
2 changed files with 13 additions and 1 deletions

View file

@ -5,6 +5,7 @@ import (
"io"
"log"
"os"
"regexp"
"strings"
"github.com/valyala/fasttemplate"
@ -93,14 +94,23 @@ func expand(m map[string]string, s string) (string, error) {
return s, nil
}
result, err := fasttemplate.ExecuteFuncStringWithErr(s, "%{", "}", func(w io.Writer, tag string) (int, error) {
if !isValidEnvVarName(tag) {
return fmt.Fprintf(w, "%%{%s}", tag)
}
v, ok := m[tag]
if !ok {
return 0, fmt.Errorf("missing %q env var", tag)
}
return w.Write([]byte(v))
return fmt.Fprintf(w, "%s", v)
})
if err != nil {
return "", err
}
return result, nil
}
func isValidEnvVarName(s string) bool {
return envVarNameRegex.MatchString(s)
}
var envVarNameRegex = regexp.MustCompile("^[a-zA-Z0-9_]+$")

View file

@ -24,6 +24,7 @@ func TestExpandTemplates(t *testing.T) {
f([]string{"foo=%{bar}", "bar=x"}, []string{"bar=x", "foo=x"})
f([]string{"a=x%{b}", "b=y%{c}z%{d}", "c=123", "d=qwe"}, []string{"a=xy123zqwe", "b=y123zqwe", "c=123", "d=qwe"})
f([]string{"a=x%{b}y", "b=z%{a}q", "c"}, []string{"a=xzxzxzxz%{a}qyqyqyqy", "b=zxzxzxzx%{b}yqyqyqyq", "c="})
f([]string{"a=%{x.y}"}, []string{"a=%{x.y}"})
}
func TestLookupEnv(t *testing.T) {
@ -70,6 +71,7 @@ func TestReplaceSuccess(t *testing.T) {
f("", "")
f("foo", "foo")
f("a %{foo}-x", "a bar-x")
f("%{foo.bar}", "%{foo.bar}")
}
func TestReplaceFailure(t *testing.T) {