Skip to content

Commit

Permalink
feat: add custom cel env support (#541)
Browse files Browse the repository at this point in the history
Signed-off-by: Charles-Edouard Brétéché <[email protected]>
  • Loading branch information
eddycharly authored Oct 8, 2024
1 parent 1149afb commit b294ee7
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 6 deletions.
12 changes: 8 additions & 4 deletions pkg/core/compilers/cel/cel.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@ type Compiler interface {
Compile(string) (Program, error)
}

type compiler struct{}
type compiler struct {
env func() (*cel.Env, error)
}

func NewCompiler() *compiler {
return &compiler{}
func NewCompiler(env func() (*cel.Env, error)) *compiler {
return &compiler{
env: env,
}
}

func (c *compiler) Compile(statement string) (Program, error) {
env, err := DefaultEnv()
env, err := c.env()
if err != nil {
return nil, err
}
Expand Down
13 changes: 13 additions & 0 deletions pkg/core/compilers/cel/cel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cel

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test_compiler_Compile(t *testing.T) {
c := NewCompiler(DefaultEnv)
_, err := c.Compile("object.?spec")
assert.NoError(t, err)
}
20 changes: 19 additions & 1 deletion pkg/core/compilers/cel/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/ext"
"github.com/jmespath-community/go-jmespath/pkg/binding"
)

var (
BindingsType = cel.OpaqueType("bindings")
DefaultEnv = sync.OnceValues(func() (*cel.Env, error) {
BaseEnv = sync.OnceValues(func() (*cel.Env, error) {
return cel.NewEnv(
cel.Variable("object", cel.DynType),
cel.Variable("bindings", BindingsType),
Expand All @@ -38,4 +39,21 @@ var (
),
)
})
DefaultEnv = sync.OnceValues(func() (*cel.Env, error) {
if env, err := BaseEnv(); err != nil {
return nil, err
} else if env, err := env.Extend(
cel.HomogeneousAggregateLiterals(),
cel.EagerlyValidateDeclarations(true),
cel.DefaultUTCTimeZone(true),
cel.CrossTypeNumericComparisons(true),
cel.OptionalTypes(),
ext.Strings(),
ext.Sets(),
); err != nil {
return nil, err
} else {
return env, nil
}
})
)
2 changes: 1 addition & 1 deletion pkg/core/compilers/compilers.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const (

var DefaultCompilers = Compilers{
Jp: jp.NewCompiler(),
Cel: cel.NewCompiler(),
Cel: cel.NewCompiler(cel.DefaultEnv),
}

type Compilers struct {
Expand Down

0 comments on commit b294ee7

Please sign in to comment.