Skip to content

Commit

Permalink
Added toYamlPretty template function
Browse files Browse the repository at this point in the history
Signed-off-by: Fred Heinecke <fred.heinecke@goteleport.com>
  • Loading branch information
fheinecke committed Dec 13, 2023
1 parent 8219565 commit 73f1dcc
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
15 changes: 15 additions & 0 deletions pkg/engine/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -49,6 +50,7 @@ func funcMap() template.FuncMap {
extra := template.FuncMap{
"toToml": toTOML,
"toYaml": toYAML,
"toYamlPretty": toYAMLPretty,
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions pkg/engine/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 73f1dcc

Please sign in to comment.