convert.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package yaml
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "gopkg.in/yaml.v3"
  18. )
  19. // ToYAML converts some object that serializes to JSON into a YAML node tree.
  20. // It's useful since it pays attention to JSON tags, unlike yaml.Unmarshal or
  21. // yaml.Node.Decode.
  22. func ToYAML(rawObj interface{}) (*yaml.Node, error) {
  23. if rawObj == nil {
  24. return &yaml.Node{Kind: yaml.ScalarNode, Value: "null", Tag: "!!null"}, nil
  25. }
  26. rawJSON, err := json.Marshal(rawObj)
  27. if err != nil {
  28. return nil, fmt.Errorf("failed to marshal object: %w", err)
  29. }
  30. var out yaml.Node
  31. if err := yaml.Unmarshal(rawJSON, &out); err != nil {
  32. return nil, fmt.Errorf("unable to unmarshal marshalled object: %w", err)
  33. }
  34. return &out, nil
  35. }
  36. // changeAll calls the given callback for all nodes in
  37. // the given YAML node tree.
  38. func changeAll(root *yaml.Node, cb func(*yaml.Node)) {
  39. cb(root)
  40. for _, child := range root.Content {
  41. changeAll(child, cb)
  42. }
  43. }
  44. // SetStyle sets the style for all nodes in the given
  45. // node tree to the given style.
  46. func SetStyle(root *yaml.Node, style yaml.Style) {
  47. changeAll(root, func(node *yaml.Node) {
  48. node.Style = style
  49. })
  50. }