...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package utils
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "io/ioutil"
22
23 "github.com/ghodss/yaml"
24 goyaml "gopkg.in/yaml.v2"
25 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
26 )
27
28 func UnstructToYaml(u *unstructured.Unstructured) ([]byte, error) {
29 bytes, err := yaml.Marshal(u)
30 if err != nil {
31 return nil, fmt.Errorf("error marshalling unstruct to yaml: %w", err)
32 }
33 return bytes, nil
34 }
35
36 func BytesToUnstruct(bytes []byte) (*unstructured.Unstructured, error) {
37 u := unstructured.Unstructured{}
38 if err := yaml.Unmarshal(bytes, &u); err != nil {
39 return nil, fmt.Errorf("error unmarshalling bytes to unstruct: %v", err)
40 }
41 return &u, nil
42 }
43
44 func ReadFileToUnstructs(filePath string) ([]*unstructured.Unstructured, error) {
45 var returnUnstructs []*unstructured.Unstructured
46 b, err := ioutil.ReadFile(filePath)
47 if err != nil {
48 return nil, err
49 }
50 yamls, err := SplitYAML(b)
51 if err != nil {
52 return nil, err
53 }
54 for _, b = range yamls {
55 u, err := BytesToUnstruct(b)
56 if err != nil {
57 return nil, err
58 }
59 returnUnstructs = append(returnUnstructs, u)
60 }
61 return returnUnstructs, nil
62 }
63
64 func SplitYAML(yamlBytes []byte) ([][]byte, error) {
65 r := bytes.NewReader(yamlBytes)
66 dec := goyaml.NewDecoder(r)
67 results := make([][]byte, 0)
68 var value map[string]interface{}
69 for eof := dec.Decode(&value); eof != io.EOF; eof = dec.Decode(&value) {
70 if eof != nil {
71 return nil, eof
72 }
73 bytes, err := goyaml.Marshal(value)
74 if err != nil {
75 return nil, fmt.Errorf("error marshalling '%v' to YAML: %v", value, err)
76 }
77 results = append(results, bytes)
78 }
79 return results, nil
80 }
81
View as plain text