github.com/splunk/qbec@v0.15.2/vm/internal/natives/yaml.go (about) 1 /* 2 Copyright 2021 Splunk Inc. 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 natives 18 19 import ( 20 "io" 21 22 v3yaml "gopkg.in/yaml.v3" 23 "k8s.io/apimachinery/pkg/util/yaml" 24 ) 25 26 // ParseYAMLDocuments parses the contents of the reader into an array of 27 // objects, one for each non-nil document in the input. 28 func ParseYAMLDocuments(reader io.Reader) ([]interface{}, error) { 29 ret := make([]interface{}, 0) 30 d := yaml.NewYAMLToJSONDecoder(reader) 31 for { 32 var doc interface{} 33 if err := d.Decode(&doc); err != nil { 34 if err == io.EOF { 35 break 36 } 37 return nil, err 38 } 39 if doc != nil { 40 ret = append(ret, doc) 41 } 42 } 43 return ret, nil 44 } 45 46 // RenderYAMLDocuments renders the supplied data as a series of YAML documents if the input is an array 47 // or a single document when it is not. Nils are excluded from output. 48 // If the caller wants an array to be rendered as a single document, 49 // they need to wrap it in an array first. Note that this function is not a drop-in replacement for 50 // data that requires ghodss/yaml to be rendered correctly. 51 func RenderYAMLDocuments(data interface{}, writer io.Writer) (retErr error) { 52 out, ok := data.([]interface{}) 53 if !ok { 54 out = []interface{}{data} 55 } 56 enc := v3yaml.NewEncoder(writer) 57 enc.SetIndent(2) 58 defer func() { 59 err := enc.Close() 60 if err == nil && retErr == nil { 61 retErr = err 62 } 63 }() 64 for _, doc := range out { 65 if doc == nil { 66 continue 67 } 68 if err := enc.Encode(doc); err != nil { 69 return err 70 } 71 } 72 return nil 73 }