From cf120e2475994f66ef5b38139f967e8a436ece9b Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Sun, 26 Jan 2025 20:46:09 +0545 Subject: [PATCH] feat: add a new method to validate cel identifier (#123) --- cel.go | 15 +++++++++++++++ cel_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 cel_test.go diff --git a/cel.go b/cel.go index c2fb0a2db..0318d07a2 100644 --- a/cel.go +++ b/cel.go @@ -2,6 +2,7 @@ package gomplate import ( "reflect" + "regexp" "github.com/flanksource/gomplate/v3/funcs" "github.com/flanksource/gomplate/v3/kubernetes" @@ -38,6 +39,10 @@ func GetCelEnv(environment map[string]any) []cel.EnvOption { // // Reference: https://github.com/google/cel-spec/blob/master/doc/langdef.md var celKeywords = map[string]struct{}{ + "true": {}, + "false": {}, + "null": {}, + "in": {}, "as": {}, "break": {}, "const": {}, @@ -57,8 +62,18 @@ var celKeywords = map[string]struct{}{ "while": {}, } +var celIdentifierRegexp = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + // IsCelKeyword returns true if the given key is a reserved word in Cel func IsCelKeyword(key string) bool { _, ok := celKeywords[key] return ok } + +func IsValidCELIdentifier(s string) bool { + if len(s) == 0 { + return false + } + + return !IsCelKeyword(s) && celIdentifierRegexp.MatchString(s) +} diff --git a/cel_test.go b/cel_test.go new file mode 100644 index 000000000..e491cd910 --- /dev/null +++ b/cel_test.go @@ -0,0 +1,33 @@ +package gomplate + +import ( + "fmt" + "testing" + + "github.com/onsi/gomega" +) + +func TestIsValidCELIdentifier(t *testing.T) { + testCases := []struct { + identifier string + valid bool + }{ + {"variable", true}, + {"_var123", true}, + {"someVariable", true}, + + {"123var", false}, + {"var-name", false}, + {"", false}, + {"var$", false}, + {"if", false}, + {"Σ_variable", false}, + } + + g := gomega.NewWithT(t) + + for i, tc := range testCases { + result := IsValidCELIdentifier(tc.identifier) + g.Expect(result).To(gomega.Equal(tc.valid), fmt.Sprintf("%d %s", i+1, tc.identifier)) + } +}