Skip to content

Commit

Permalink
WIP: add code runner for configuration code execution
Browse files Browse the repository at this point in the history
  • Loading branch information
adohe committed Feb 19, 2024
1 parent 99168ac commit f180d59
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/cmd/generate/run/fake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package run
71 changes: 71 additions & 0 deletions pkg/cmd/generate/run/run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package run

import (
kcl "kcl-lang.io/kcl-go"
kclpkg "kcl-lang.io/kcl-go/pkg/kcl"
"kcl-lang.io/kpm/pkg/api"
"kcl-lang.io/kpm/pkg/opt"
)

// CodeRunner compiles and runs the target DSL based configuration code
// and returns configuration data in plain format.
type CodeRunner interface {
Run(workingDir string, arguments map[string]string) ([]byte, error)
}

// KPMRunner should implement the CodeRunner interface.
var _ CodeRunner = &KPMRunner{}

// KPMRunner implements the CodeRunner interface.
type KPMRunner struct{}

// Run calls KPM api to compile and run KCL based configuration code.
func (r *KPMRunner) Run(workingDir string, arguments map[string]string) ([]byte, error) {
optList, err := buildKCLOptions(workingDir, arguments)
if err != nil {
return nil, err
}

result, err := api.RunWithOpts(
opt.WithKclOption(*kclpkg.NewOption().Merge(optList...)),
opt.WithNoSumCheck(true),
opt.WithLogWriter(nil),
)
if err != nil {
return nil, err
}

return []byte(result.GetRawYamlResult()), nil
}

// buildKCLOptions returns list of KCL options.
func buildKCLOptions(workingDir string, arguments map[string]string) ([]kcl.Option, error) {
optList := make([]kcl.Option, 0)

// build arguments option
for k, v := range arguments {
argStr := k + "=" + v
withOpt := kcl.WithOptions(argStr)
if withOpt.Err != nil {
return nil, withOpt.Err
}

optList = append(optList, withOpt)
}

// build workDir option
withOpt := kcl.WithWorkDir(workingDir)
if withOpt.Err != nil {
return nil, withOpt.Err
}
optList = append(optList, withOpt)

// eliminate null values in the result
withOpt = kcl.WithDisableNone(true)
if withOpt.Err != nil {
return nil, withOpt.Err
}
optList = append(optList, withOpt)

return optList, nil
}
1 change: 1 addition & 0 deletions pkg/cmd/generate/run/run_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package run

0 comments on commit f180d59

Please sign in to comment.