mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-05-04 19:17:37 +08:00
parent
a4992c3f79
commit
8eefcc8cc8
@ -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
|
||||||
}
|
}
|
||||||
|
@ -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 {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user