Skip to content

Commit

Permalink
feat: add a new method to validate cel identifier (#123)
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe authored Jan 26, 2025
1 parent 062a9ec commit cf120e2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
15 changes: 15 additions & 0 deletions cel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gomplate

import (
"reflect"
"regexp"

"github.com/flanksource/gomplate/v3/funcs"
"github.com/flanksource/gomplate/v3/kubernetes"
Expand Down Expand Up @@ -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": {},
Expand All @@ -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)
}
33 changes: 33 additions & 0 deletions cel_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
}

0 comments on commit cf120e2

Please sign in to comment.