diff --git a/kclvm.go b/kclvm.go index 37814e00..7ff9fcca 100644 --- a/kclvm.go +++ b/kclvm.go @@ -31,6 +31,8 @@ KCL Go SDK package kclvm import ( + "io" + "kcl-lang.io/kcl-go/pkg/kcl" "kcl-lang.io/kcl-go/pkg/kclvm_runtime" "kcl-lang.io/kcl-go/pkg/tools/format" @@ -122,6 +124,11 @@ func WithSortKeys(sortKeys bool) Option { return kcl.WithSortKeys(sortKeys) } +// WithLogger returns a Option which hold a logger. +func WithLogger(l io.Writer) Option { + return kcl.WithLogger(l) +} + // FormatCode returns the formatted code. func FormatCode(code interface{}) ([]byte, error) { return format.FormatCode(code) diff --git a/kclvm_test.go b/kclvm_test.go index 50c15a79..2d53b268 100644 --- a/kclvm_test.go +++ b/kclvm_test.go @@ -3,6 +3,7 @@ package kclvm_test import ( + "bytes" "flag" "os" "path/filepath" @@ -489,3 +490,17 @@ func TestWithExternalpkg(t *testing.T) { assert2.Equal(t, "[{\"a\": \"Hello External_1 World!\", \"b\": \"Hello External_2 World!\"}]", result.GetRawJsonResult()) assert2.Equal(t, "a: Hello External_1 World!\nb: Hello External_2 World!", result.GetRawYamlResult()) } + +func TestWithLogger(t *testing.T) { + file, err := filepath.Abs("./testdata/test_print/main.k") + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + result, err := kcl.Run(file, kcl.WithLogger(&buf)) + if err != nil { + t.Fatal(err) + } + assert2.Equal(t, "hello: world", result.GetRawYamlResult()) + assert2.Equal(t, "Hello world\n", buf.String()) +} diff --git a/pkg/kcl/opt.go b/pkg/kcl/opt.go index 7fa1acff..f853ca66 100644 --- a/pkg/kcl/opt.go +++ b/pkg/kcl/opt.go @@ -279,7 +279,9 @@ func (p *Option) Merge(opts ...Option) *Option { if opt.ExternalPkgs != nil { p.ExternalPkgs = append(p.ExternalPkgs, opt.ExternalPkgs...) } - p.logger = opt.logger + if opt.logger != nil { + p.logger = opt.logger + } } return p } diff --git a/testdata/test_print/kcl.mod b/testdata/test_print/kcl.mod new file mode 100644 index 00000000..94dc7fcd --- /dev/null +++ b/testdata/test_print/kcl.mod @@ -0,0 +1,3 @@ +[package] +name = "test_print" + diff --git a/testdata/test_print/main.k b/testdata/test_print/main.k new file mode 100644 index 00000000..c2cb4798 --- /dev/null +++ b/testdata/test_print/main.k @@ -0,0 +1,2 @@ +hello = "world" +print("Hello world")