diff --git a/go.mod b/go.mod index 6eef690da..dca6d3b08 100644 --- a/go.mod +++ b/go.mod @@ -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 ( diff --git a/go.sum b/go.sum index 2ed2d3f8f..a6d1e1b1b 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/pkg/engine/funcs.go b/pkg/engine/funcs.go index 8f05a3a1d..6b3bab4ee 100644 --- a/pkg/engine/funcs.go +++ b/pkg/engine/funcs.go @@ -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 diff --git a/pkg/engine/funcs_test.go b/pkg/engine/funcs_test.go index 29bc121b5..ecaee7260 100644 --- a/pkg/engine/funcs_test.go +++ b/pkg/engine/funcs_test.go @@ -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",