Added `toYamlPretty` template function

Signed-off-by: Fred Heinecke <fred.heinecke@goteleport.com>
pull/12583/head
Fred Heinecke 1 year ago
parent 8219565249
commit 73f1dcc1d9

@ -45,7 +45,7 @@ require (
k8s.io/klog/v2 v2.100.1
k8s.io/kubectl v0.28.2
oras.land/oras-go v1.2.4
sigs.k8s.io/yaml v1.3.0
sigs.k8s.io/yaml v1.4.0
)
require (

@ -555,3 +555,5 @@ sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kF
sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=

@ -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.
@ -49,6 +50,7 @@ func funcMap() template.FuncMap {
extra := template.FuncMap{
"toToml": toTOML,
"toYaml": toYAML,
"toYamlPretty": toYAMLPretty,
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
@ -88,6 +90,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