Skip to content

Commit

Permalink
fix: structs as cel env var
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Jul 21, 2023
1 parent 19f81d0 commit 097c035
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
15 changes: 14 additions & 1 deletion template.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,23 @@ func RunTemplate(environment map[string]any, template Template) (string, error)
if err != nil {
return "", err
}
out, _, err := prg.Eval(environment)

// Convert environment to json otherwise structs will not be casted to cel-go's ref.Val
envJSONRaw, err := json.Marshal(environment)
if err != nil {
return "", fmt.Errorf("failed to marshal environment: %v", err)
}

var envJSON map[string]any
if err := json.Unmarshal(envJSONRaw, &envJSON); err != nil {
return "", fmt.Errorf("failed to unmarshal environment: %v", err)
}

out, _, err := prg.Eval(envJSON)
if err != nil {
return "", err
}

return fmt.Sprintf("%v", out.Value()), nil
}

Expand Down
23 changes: 23 additions & 0 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ func TestGomplate(t *testing.T) {
}

func TestCel(t *testing.T) {
type Address struct {
City string `json:"city"`
}

type Person struct {
Name string `json:"name"`
Address Address `json:"address"`
}

tests := []struct {
env map[string]interface{}
expression string
Expand Down Expand Up @@ -101,6 +110,20 @@ func TestCel(t *testing.T) {
{nil, `"hello, world".replace("world", "team")`, "hello, team"}, // strings lib
{nil, `sets.contains([1, 2, 3, 4], [2, 3])`, "true"}, // sets lib
{nil, `[1,2,3,4].slice(1, 3)`, "[2 3]"}, // lists lib

// Support structs as environment var (by default they are not)
{
map[string]any{
"results": Person{
Name: "Aditya",
Address: Address{
City: "Kathmandu",
},
},
},
`results.address.city == "Kathmandu" && results.name == "Aditya"`,
"true",
},
}

for _, tc := range tests {
Expand Down

0 comments on commit 097c035

Please sign in to comment.