yaml.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package template
  13. import (
  14. "strings"
  15. "sigs.k8s.io/yaml"
  16. )
  17. // toYAML takes an interface, marshals it to yaml, and returns a string. It will
  18. // always return a string, even on marshal error (empty string).
  19. //
  20. // This is designed to be called from a template.
  21. func toYAML(v interface{}) string {
  22. data, err := yaml.Marshal(v)
  23. if err != nil {
  24. // Swallow errors inside of a template.
  25. return ""
  26. }
  27. return strings.TrimSuffix(string(data), "\n")
  28. }
  29. // fromYAML converts a YAML document into a map[string]interface{}.
  30. //
  31. // This is not a general-purpose YAML parser, and will not parse all valid
  32. // YAML documents. Additionally, because its intended use is within templates
  33. // it tolerates errors. It will insert the returned error message string into
  34. // m["Error"] in the returned map.
  35. func fromYAML(str string) map[string]interface{} {
  36. m := map[string]interface{}{}
  37. if err := yaml.Unmarshal([]byte(str), &m); err != nil {
  38. m["Error"] = err.Error()
  39. }
  40. return m
  41. }