diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index ddeb2425..6b3a48bc 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -1939,3 +1939,19 @@ func TestRunInVendor(t *testing.T) { assert.Equal(t, buf.String(), "") assert.Equal(t, res.GetRawYamlResult(), "The_first_kcl_program: Hello World!") } + +func TestRunWithLogger(t *testing.T) { + pkgPath := getTestDir("test_run_with_logger") + kpmcli, err := NewKpmClient() + assert.Equal(t, err, nil) + + logbuf := new(bytes.Buffer) + + _, err = kpmcli.Run( + WithWorkDir(pkgPath), + WithLogger(logbuf), + ) + + assert.Equal(t, err, nil) + assert.Equal(t, logbuf.String(), "Hello, World!\n") +} diff --git a/pkg/client/run.go b/pkg/client/run.go index 653bd28a..dcddbd44 100644 --- a/pkg/client/run.go +++ b/pkg/client/run.go @@ -65,6 +65,7 @@ package client import ( "errors" "fmt" + "io" "os" "path/filepath" @@ -88,6 +89,16 @@ type RunOptions struct { type RunOption func(*RunOptions) error +func WithLogger(l io.Writer) RunOption { + return func(ro *RunOptions) error { + if ro.Option == nil { + ro.Option = kcl.NewOption() + } + ro.Merge(kcl.WithLogger(l)) + return nil + } +} + // WithWorkDir sets the work directory for running the kcl package. func WithWorkDir(workDir string) RunOption { return func(ro *RunOptions) error { diff --git a/pkg/client/test_data/test_run_with_logger/main.k b/pkg/client/test_data/test_run_with_logger/main.k new file mode 100644 index 00000000..4103a1fe --- /dev/null +++ b/pkg/client/test_data/test_run_with_logger/main.k @@ -0,0 +1 @@ +print("Hello, World!") \ No newline at end of file