github.com/minio/controller-tools@v0.4.7/pkg/schemapatcher/internal/yaml/convert.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 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 yaml 18 19 import ( 20 "encoding/json" 21 "fmt" 22 23 "gopkg.in/yaml.v3" 24 ) 25 26 // ToYAML converts some object that serializes to JSON into a YAML node tree. 27 // It's useful since it pays attention to JSON tags, unlike yaml.Unmarshal or 28 // yaml.Node.Decode. 29 func ToYAML(rawObj interface{}) (*yaml.Node, error) { 30 if rawObj == nil { 31 return &yaml.Node{Kind: yaml.ScalarNode, Value: "null", Tag: "!!null"}, nil 32 } 33 34 rawJSON, err := json.Marshal(rawObj) 35 if err != nil { 36 return nil, fmt.Errorf("failed to marshal object: %w", err) 37 } 38 39 var out yaml.Node 40 if err := yaml.Unmarshal(rawJSON, &out); err != nil { 41 return nil, fmt.Errorf("unable to unmarshal marshalled object: %w", err) 42 } 43 return &out, nil 44 } 45 46 // changeAll calls the given callback for all nodes in 47 // the given YAML node tree. 48 func changeAll(root *yaml.Node, cb func(*yaml.Node)) { 49 cb(root) 50 for _, child := range root.Content { 51 changeAll(child, cb) 52 } 53 } 54 55 // SetStyle sets the style for all nodes in the given 56 // node tree to the given style. 57 func SetStyle(root *yaml.Node, style yaml.Style) { 58 changeAll(root, func(node *yaml.Node) { 59 node.Style = style 60 }) 61 }