Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add a new method to validate cel identifier #123

Merged
merged 1 commit into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
}
}
Loading