Merge pull request #12583 from fheinecke/feat/add-toyamlpretty-1

pull/13330/head
Scott Rigby 2 weeks ago committed by GitHub
commit 54fc7fbefd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -25,6 +25,7 @@ import (
"github.com/BurntSushi/toml"
"github.com/Masterminds/sprig/v3"
"sigs.k8s.io/yaml"
goYaml "sigs.k8s.io/yaml/goyaml.v3"
)
// funcMap returns a mapping of all of the functions that Engine has.
@ -50,6 +51,7 @@ func funcMap() template.FuncMap {
"toToml": toTOML,
"fromToml": fromTOML,
"toYaml": toYAML,
"toYamlPretty": toYAMLPretty,
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
@ -89,6 +91,19 @@ func toYAML(v interface{}) string {
return strings.TrimSuffix(string(data), "\n")
}
func toYAMLPretty(v interface{}) string {
var data bytes.Buffer
encoder := goYaml.NewEncoder(&data)
encoder.SetIndent(2)
err := encoder.Encode(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return strings.TrimSuffix(data.String(), "\n")
}
// fromYAML converts a YAML document into a map[string]interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid

@ -33,6 +33,10 @@ func TestFuncs(t *testing.T) {
tpl: `{{ toYaml . }}`,
expect: `foo: bar`,
vars: map[string]interface{}{"foo": "bar"},
}, {
tpl: `{{ toYamlPretty . }}`,
expect: "baz:\n - 1\n - 2\n - 3",
vars: map[string]interface{}{"baz": []int{1, 2, 3}},
}, {
tpl: `{{ toToml . }}`,
expect: "foo = \"bar\"\n",

Loading…
Cancel
Save