mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2024-11-21 14:44:00 +00:00
lib/envtemplate: allow non-env var names inside "%{ ... }"
This commit is contained in:
parent
dd88c628aa
commit
116811d761
2 changed files with 13 additions and 1 deletions
|
@ -5,6 +5,7 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/valyala/fasttemplate"
|
"github.com/valyala/fasttemplate"
|
||||||
|
@ -93,14 +94,23 @@ func expand(m map[string]string, s string) (string, error) {
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
result, err := fasttemplate.ExecuteFuncStringWithErr(s, "%{", "}", func(w io.Writer, tag string) (int, error) {
|
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]
|
v, ok := m[tag]
|
||||||
if !ok {
|
if !ok {
|
||||||
return 0, fmt.Errorf("missing %q env var", tag)
|
return 0, fmt.Errorf("missing %q env var", tag)
|
||||||
}
|
}
|
||||||
return w.Write([]byte(v))
|
return fmt.Fprintf(w, "%s", v)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isValidEnvVarName(s string) bool {
|
||||||
|
return envVarNameRegex.MatchString(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
var envVarNameRegex = regexp.MustCompile("^[a-zA-Z0-9_]+$")
|
||||||
|
|
|
@ -24,6 +24,7 @@ func TestExpandTemplates(t *testing.T) {
|
||||||
f([]string{"foo=%{bar}", "bar=x"}, []string{"bar=x", "foo=x"})
|
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}", "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%{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) {
|
func TestLookupEnv(t *testing.T) {
|
||||||
|
@ -70,6 +71,7 @@ func TestReplaceSuccess(t *testing.T) {
|
||||||
f("", "")
|
f("", "")
|
||||||
f("foo", "foo")
|
f("foo", "foo")
|
||||||
f("a %{foo}-x", "a bar-x")
|
f("a %{foo}-x", "a bar-x")
|
||||||
|
f("%{foo.bar}", "%{foo.bar}")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReplaceFailure(t *testing.T) {
|
func TestReplaceFailure(t *testing.T) {
|
||||||
|
|
Loading…
Reference in a new issue