Skip to content

Commit 4ae8f11

Browse files
feat: compile expressions when unmarshaling (#1845) (#1847)
Signed-off-by: Charles-Edouard Brétéché <[email protected]> Co-authored-by: Charles-Edouard Brétéché <[email protected]>
1 parent 9abd6a7 commit 4ae8f11

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

pkg/apis/v1alpha1/types.go

+30
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ package v1alpha1
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
67
"regexp"
78

89
"github.com/jmespath-community/go-jmespath/pkg/binding"
10+
"github.com/jmespath-community/go-jmespath/pkg/parsing"
911
"github.com/kyverno/chainsaw/pkg/expressions"
1012
"github.com/kyverno/kyverno-json/pkg/apis/policy/v1alpha1"
1113
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -66,6 +68,34 @@ type Expectation struct {
6668
// Expression defines an expression to be used in string fields.
6769
type Expression string
6870

71+
func (e *Expression) MarshalJSON() ([]byte, error) {
72+
if e == nil {
73+
return nil, nil
74+
}
75+
return json.Marshal(string(*e))
76+
}
77+
78+
func (e *Expression) UnmarshalJSON(data []byte) error {
79+
var statement string
80+
err := json.Unmarshal(data, &statement)
81+
if err != nil {
82+
return err
83+
}
84+
*e = Expression(statement)
85+
expression := expressions.Parse(context.TODO(), statement)
86+
if expression == nil {
87+
return nil
88+
}
89+
if expression.Engine == "" {
90+
return nil
91+
}
92+
parser := parsing.NewParser()
93+
if _, err := parser.Parse(statement); err != nil {
94+
return err
95+
}
96+
return nil
97+
}
98+
6999
func (e Expression) Value(ctx context.Context, bindings binding.Bindings) (string, error) {
70100
return expressions.String(ctx, string(e), bindings)
71101
}

0 commit comments

Comments
 (0)