Skip to content

Commit cf120e2

Browse files
authored
feat: add a new method to validate cel identifier (#123)
1 parent 062a9ec commit cf120e2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

cel.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package gomplate
22

33
import (
44
"reflect"
5+
"regexp"
56

67
"github.com/flanksource/gomplate/v3/funcs"
78
"github.com/flanksource/gomplate/v3/kubernetes"
@@ -38,6 +39,10 @@ func GetCelEnv(environment map[string]any) []cel.EnvOption {
3839
//
3940
// Reference: https://github.com/google/cel-spec/blob/master/doc/langdef.md
4041
var celKeywords = map[string]struct{}{
42+
"true": {},
43+
"false": {},
44+
"null": {},
45+
"in": {},
4146
"as": {},
4247
"break": {},
4348
"const": {},
@@ -57,8 +62,18 @@ var celKeywords = map[string]struct{}{
5762
"while": {},
5863
}
5964

65+
var celIdentifierRegexp = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
66+
6067
// IsCelKeyword returns true if the given key is a reserved word in Cel
6168
func IsCelKeyword(key string) bool {
6269
_, ok := celKeywords[key]
6370
return ok
6471
}
72+
73+
func IsValidCELIdentifier(s string) bool {
74+
if len(s) == 0 {
75+
return false
76+
}
77+
78+
return !IsCelKeyword(s) && celIdentifierRegexp.MatchString(s)
79+
}

cel_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package gomplate
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/onsi/gomega"
8+
)
9+
10+
func TestIsValidCELIdentifier(t *testing.T) {
11+
testCases := []struct {
12+
identifier string
13+
valid bool
14+
}{
15+
{"variable", true},
16+
{"_var123", true},
17+
{"someVariable", true},
18+
19+
{"123var", false},
20+
{"var-name", false},
21+
{"", false},
22+
{"var$", false},
23+
{"if", false},
24+
{"Σ_variable", false},
25+
}
26+
27+
g := gomega.NewWithT(t)
28+
29+
for i, tc := range testCases {
30+
result := IsValidCELIdentifier(tc.identifier)
31+
g.Expect(result).To(gomega.Equal(tc.valid), fmt.Sprintf("%d %s", i+1, tc.identifier))
32+
}
33+
}

0 commit comments

Comments
 (0)