-
Notifications
You must be signed in to change notification settings - Fork 78
/
kcl.go
57 lines (45 loc) · 1.54 KB
/
kcl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package engine
import (
"fmt"
yamlv2 "gopkg.in/yaml.v2"
yamlv3 "gopkg.in/yaml.v3"
"github.com/pkg/errors"
kcl "kusionstack.io/kclvm-go"
"kusionstack.io/kusion/pkg/engine/models"
"kusionstack.io/kusion/pkg/log"
jsonUtil "kusionstack.io/kusion/pkg/util/json"
)
const MaxLogLength = 3751
func ConvertKCLResult2Resources(resourceYAMLs []kcl.KCLResult) (*models.Spec, error) {
resources := []models.Resource{}
for _, resourcesYamlMap := range resourceYAMLs {
// Convert kcl result to yaml string
msg := jsonUtil.MustMarshal2String(resourcesYamlMap)
if len(msg) > MaxLogLength {
msg = msg[0:MaxLogLength]
}
log.Infof("convertKCLResult2Resources resource:%v", msg)
// Use yamlv3.Marshal, and then yamlv3.Unmarshal, something will report an error:
// "did not find expected '-' indicator"
// So, use yamlv2.Marshal and yamlv3.Unmarshal.
yamlByte, err := yamlv2.Marshal(resourcesYamlMap)
if err != nil {
return nil, fmt.Errorf("yaml marshal failed. %v,%w", jsonUtil.MustMarshal2String(resourcesYamlMap), err)
}
// Parse yaml string as Resource
item := &models.Resource{}
err = yamlv3.Unmarshal(yamlByte, item)
if err != nil {
return nil, err
}
// TODO: any other better judgement here?
if item.Attributes == nil {
item, _, err = NewRequestResourceForKubernetes(resourcesYamlMap)
if err != nil {
return nil, errors.Wrap(err, "compile result format error (neither kubernetes nor engine resource format)")
}
}
resources = append(resources, *item)
}
return &models.Spec{Resources: resources}, nil
}