yaml.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. Copyright © The ESO 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. https://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 template
  14. import (
  15. "strings"
  16. "sigs.k8s.io/yaml"
  17. )
  18. // toYAML takes an interface, marshals it to yaml, and returns a string. It will
  19. // always return a string, even on marshal error (empty string).
  20. //
  21. // This is designed to be called from a template.
  22. func toYAML(v any) string {
  23. data, err := yaml.Marshal(v)
  24. if err != nil {
  25. // Swallow errors inside of a template.
  26. return ""
  27. }
  28. return strings.TrimSuffix(string(data), "\n")
  29. }
  30. // fromYAML converts a YAML document into a map[string]any.
  31. //
  32. // This is not a general-purpose YAML parser, and will not parse all valid
  33. // YAML documents. Additionally, because its intended use is within templates
  34. // it tolerates errors. It will insert the returned error message string into
  35. // m["Error"] in the returned map.
  36. func fromYAML(str string) map[string]any {
  37. m := map[string]any{}
  38. if err := yaml.Unmarshal([]byte(str), &m); err != nil {
  39. m["Error"] = err.Error()
  40. }
  41. return m
  42. }