forked from hairyhenderson/gomplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcel.go
79 lines (67 loc) · 1.85 KB
/
cel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package gomplate
import (
"reflect"
"regexp"
"github.com/flanksource/gomplate/v3/funcs"
"github.com/flanksource/gomplate/v3/kubernetes"
"github.com/flanksource/gomplate/v3/strings"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/ext"
)
var typeAdapters = []cel.EnvOption{}
func RegisterType(i any) {
typeAdapters = append(typeAdapters, ext.NativeTypes(reflect.TypeOf(i)))
}
func GetCelEnv(environment map[string]any) []cel.EnvOption {
// Generated functions
var opts = funcs.CelEnvOption
opts = append(opts, kubernetes.Library()...)
opts = append(opts, ext.Strings(), ext.Encoders(), ext.Lists(), ext.Math(), ext.Sets())
opts = append(opts, cel.StdLib())
opts = append(opts, cel.OptionalTypes())
opts = append(opts, strings.Library...)
opts = append(opts, typeAdapters...)
// Load input as variables
for k := range environment {
opts = append(opts, cel.Variable(k, cel.AnyType))
}
return opts
}
// The following identifiers are reserved to allow easier embedding of CEL into a host language.
//
// Reference: https://github.com/google/cel-spec/blob/master/doc/langdef.md
var celKeywords = map[string]struct{}{
"true": {},
"false": {},
"null": {},
"in": {},
"as": {},
"break": {},
"const": {},
"continue": {},
"else": {},
"for": {},
"function": {},
"if": {},
"import": {},
"let": {},
"loop": {},
"namespace": {},
"package": {},
"return": {},
"var": {},
"void": {},
"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)
}