Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make WithContext work for methods on env struct #602

Merged
merged 1 commit into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions patcher/with_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,18 @@ func (w WithContext) Visit(node *ast.Node) {
if fn.Kind() != reflect.Func {
return
}
if fn.NumIn() == 0 {
return
}
if fn.In(0).String() != "context.Context" {
switch fn.NumIn() {
case 0:
return
case 1:
if fn.In(0).String() != "context.Context" {
return
}
default:
if fn.In(0).String() != "context.Context" &&
fn.In(1).String() != "context.Context" {
return
}
}
ast.Patch(node, &ast.CallNode{
Callee: call.Callee,
Expand Down
24 changes: 24 additions & 0 deletions patcher/with_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ func TestWithContext_with_env_Function(t *testing.T) {
require.Equal(t, 42, output)
}

type testEnvContext struct {
Context context.Context `expr:"ctx"`
}

func (testEnvContext) Fn(ctx context.Context, a int) int {
return ctx.Value("value").(int) + a
}

func TestWithContext_env_struct(t *testing.T) {
withContext := patcher.WithContext{Name: "ctx"}

program, err := expr.Compile(`Fn(40)`, expr.Env(testEnvContext{}), expr.Patch(withContext))
require.NoError(t, err)

ctx := context.WithValue(context.Background(), "value", 2)
env := testEnvContext{
Context: ctx,
}

output, err := expr.Run(program, env)
require.NoError(t, err)
require.Equal(t, 42, output)
}

type TestFoo struct {
contextValue int
}
Expand Down
Loading