Skip to content

Commit 73f1dcc

Browse files
committedDec 13, 2023
Added toYamlPretty template function
Signed-off-by: Fred Heinecke <fred.heinecke@goteleport.com>
1 parent 8219565 commit 73f1dcc

File tree

4 files changed

+22
-1
lines changed

4 files changed

+22
-1
lines changed
 

‎go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ require (
4545
k8s.io/klog/v2 v2.100.1
4646
k8s.io/kubectl v0.28.2
4747
oras.land/oras-go v1.2.4
48-
sigs.k8s.io/yaml v1.3.0
48+
sigs.k8s.io/yaml v1.4.0
4949
)
5050

5151
require (

‎go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -555,3 +555,5 @@ sigs.k8s.io/structured-merge-diff/v4 v4.2.3 h1:PRbqxJClWWYMNV1dhaG4NsibJbArud9kF
555555
sigs.k8s.io/structured-merge-diff/v4 v4.2.3/go.mod h1:qjx8mGObPmV2aSZepjQjbmb2ihdVs8cGKBraizNC69E=
556556
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
557557
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
558+
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
559+
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=

‎pkg/engine/funcs.go

+15
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/BurntSushi/toml"
2626
"github.com/Masterminds/sprig/v3"
2727
"sigs.k8s.io/yaml"
28+
goYaml "sigs.k8s.io/yaml/goyaml.v3"
2829
)
2930

3031
// funcMap returns a mapping of all of the functions that Engine has.
@@ -49,6 +50,7 @@ func funcMap() template.FuncMap {
4950
extra := template.FuncMap{
5051
"toToml": toTOML,
5152
"toYaml": toYAML,
53+
"toYamlPretty": toYAMLPretty,
5254
"fromYaml": fromYAML,
5355
"fromYamlArray": fromYAMLArray,
5456
"toJson": toJSON,
@@ -88,6 +90,19 @@ func toYAML(v interface{}) string {
8890
return strings.TrimSuffix(string(data), "\n")
8991
}
9092

93+
func toYAMLPretty(v interface{}) string {
94+
var data bytes.Buffer
95+
encoder := goYaml.NewEncoder(&data)
96+
encoder.SetIndent(2)
97+
err := encoder.Encode(v)
98+
99+
if err != nil {
100+
// Swallow errors inside of a template.
101+
return ""
102+
}
103+
return strings.TrimSuffix(data.String(), "\n")
104+
}
105+
91106
// fromYAML converts a YAML document into a map[string]interface{}.
92107
//
93108
// This is not a general-purpose YAML parser, and will not parse all valid

‎pkg/engine/funcs_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ func TestFuncs(t *testing.T) {
3333
tpl: `{{ toYaml . }}`,
3434
expect: `foo: bar`,
3535
vars: map[string]interface{}{"foo": "bar"},
36+
}, {
37+
tpl: `{{ toYamlPretty . }}`,
38+
expect: "baz:\n - 1\n - 2\n - 3",
39+
vars: map[string]interface{}{"baz": []int{1, 2, 3}},
3640
}, {
3741
tpl: `{{ toToml . }}`,
3842
expect: "foo = \"bar\"\n",

0 commit comments

Comments
 (0)
Please sign in to comment.