1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00

config: impl env placeholder with default value

Fixes #1358
This commit is contained in:
wdvxdr 2022-02-09 13:41:19 +08:00
parent a4992c3f79
commit 8eefcc8cc8
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6
2 changed files with 23 additions and 7 deletions

View File

@ -152,12 +152,23 @@ func generateConfig() {
// os.ExpandEnv 字符 $ 无法逃逸 // os.ExpandEnv 字符 $ 无法逃逸
// https://github.com/golang/go/issues/43482 // https://github.com/golang/go/issues/43482
func expand(s string, mapping func(string) string) string { func expand(s string, mapping func(string) string) string {
r := regexp.MustCompile(`\${([a-zA-Z_]+[a-zA-Z0-9_]*)}`) r := regexp.MustCompile(`\${([a-zA-Z_]+[a-zA-Z0-9_:]*)}`)
re := r.FindAllStringSubmatch(s, -1) return r.ReplaceAllStringFunc(s, func(s string) string {
for _, i := range re { s = strings.Trim(s, "${}")
if len(i) == 2 { // todo: use strings.Cut once go1.18 is released
s = strings.ReplaceAll(s, i[0], mapping(i[1])) placeholder, default_, ok := cut(s, ":")
m := mapping(placeholder)
if ok && m == "" {
return default_
} }
} return m
return s })
}
func cut(s, sep string) (before, after string, found bool) {
if i := strings.Index(s, sep); i >= 0 {
return s[:i], s[i+len(sep):], true
}
return s, "", false
} }

View File

@ -21,6 +21,11 @@ func Test_expand(t *testing.T) {
mapping: strings.ToUpper, mapping: strings.ToUpper,
expected: "$123", expected: "$123",
}, },
{
src: "foo: ${bar:123456}",
mapping: func(s string) string { return "" },
expected: "foo: 123456",
},
} }
for i, tt := range tests { for i, tt := range tests {
if got := expand(tt.src, tt.mapping); got != tt.expected { if got := expand(tt.src, tt.mapping); got != tt.expected {