match expr helper (#2126)

* match expr helper
This commit is contained in:
Thibault "bui" Koechlin 2023-03-21 10:39:17 +01:00 committed by GitHub
parent 86971da274
commit d87f088b8f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View file

@ -123,6 +123,7 @@ func GetExprEnv(ctx map[string]interface{}) map[string]interface{} {
"Get": Get,
"String": ToString,
"Distance": Distance,
"Match": Match,
}
for k, v := range ctx {
ExprLib[k] = v
@ -493,3 +494,28 @@ func ToString(value interface{}) string {
}
return s
}
func Match(pattern, name string) bool {
var matched bool
if pattern == "" {
return name == ""
}
if name == "" {
if pattern == "*" || pattern == "" {
return true
}
return false
}
if pattern[0] == '*' {
for i := 0; i <= len(name); i++ {
if matched = Match(pattern[1:], name[i:]); matched {
return matched
}
}
return matched
}
if pattern[0] == '?' || pattern[0] == name[0] {
return Match(pattern[1:], name[1:])
}
return matched
}

View file

@ -125,6 +125,38 @@ func TestVisitor(t *testing.T) {
}
}
func TestMatch(t *testing.T) {
tests := []struct {
glob string
val string
ret bool
}{
{"foo", "foo", true},
{"foo", "bar", false},
{"foo*", "foo", true},
{"foo*", "foobar", true},
{"foo*", "barfoo", false},
{"foo*", "bar", false},
{"*foo", "foo", true},
{"*foo", "barfoo", true},
{"foo*r", "foobar", true},
{"foo*r", "foobazr", true},
{"foo?ar", "foobar", true},
{"foo?ar", "foobazr", false},
{"foo?ar", "foobaz", false},
{"*foo?ar?", "foobar", false},
{"*foo?ar?", "foobare", true},
{"*foo?ar?", "rafoobar", false},
{"*foo?ar?", "rafoobare", true},
}
for _, test := range tests {
ret := Match(test.glob, test.val)
if isOk := assert.Equal(t, test.ret, ret); !isOk {
t.Fatalf("pattern:%s val:%s NOK %t != %t", test.glob, test.val, ret, test.ret)
}
}
}
func TestDistanceHelper(t *testing.T) {
//one set of coord is empty