github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/tools/kubeyaml.go (about) 1 /* 2 Copyright 2018 Mirantis 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tools 18 19 import ( 20 "bytes" 21 "encoding/json" 22 23 "github.com/ghodss/yaml" 24 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 25 "k8s.io/apimachinery/pkg/runtime" 26 "k8s.io/client-go/kubernetes/scheme" 27 ) 28 29 // LoadYaml loads a k8s YAML data and returns a slice of k8s objects 30 func LoadYaml(data []byte) ([]runtime.Object, error) { 31 parts := bytes.Split(data, []byte("---")) 32 var r []runtime.Object 33 for _, part := range parts { 34 part = bytes.TrimSpace(part) 35 if len(part) == 0 { 36 continue 37 } 38 obj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil) 39 if err != nil { 40 return nil, err 41 } 42 r = append(r, obj) 43 } 44 return r, nil 45 } 46 47 // ToYaml converts a slice of k8s objects to YAML 48 func ToYaml(objs []runtime.Object) ([]byte, error) { 49 var out bytes.Buffer 50 for _, obj := range objs { 51 // the idea is from https://github.com/ant31/crd-validation/blob/master/pkg/cli-utils.go 52 bs, err := json.Marshal(obj) 53 if err != nil { 54 return nil, err 55 } 56 57 var us unstructured.Unstructured 58 if err := json.Unmarshal(bs, &us.Object); err != nil { 59 return nil, err 60 } 61 62 unstructured.RemoveNestedField(us.Object, "status") 63 64 bs, err = yaml.Marshal(us.Object) 65 if err != nil { 66 return nil, err 67 } 68 out.WriteString("---\n") 69 out.Write(bs) 70 out.WriteString("\n") 71 } 72 return out.Bytes(), nil 73 }