Ver código fonte

match expr helper (#2126)

* match expr helper
Thibault "bui" Koechlin 2 anos atrás
pai
commit
d87f088b8f
2 arquivos alterados com 58 adições e 0 exclusões
  1. 26 0
      pkg/exprhelpers/exprlib.go
  2. 32 0
      pkg/exprhelpers/exprlib_test.go

+ 26 - 0
pkg/exprhelpers/exprlib.go

@@ -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
+}

+ 32 - 0
pkg/exprhelpers/exprlib_test.go

@@ -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