Skip to content

Commit

Permalink
Pipeline: Add 'toYaml' function
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Kosegi <richard.kosegi@gmail.com>
  • Loading branch information
rkosegi committed Aug 6, 2024
1 parent dad8dc7 commit 7f3fb0d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 9 additions & 2 deletions pipeline/template_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package pipeline

import (
"bytes"
"github.com/rkosegi/yaml-toolkit/utils"
"strconv"
"strings"
"text/template"
Expand All @@ -40,12 +41,18 @@ func tplFunc(tmpl *template.Template) func(string, interface{}) (string, error)
}
}

func toYamlFunc(v interface{}) (string, error) {
var buf strings.Builder
err := utils.NewYamlEncoder(&buf).Encode(v)
return strings.TrimSuffix(buf.String(), "\n"), err
}

func renderTemplate(tmplStr string, data interface{}, fm template.FuncMap) (string, error) {
tmpl := template.New("tmpl").Funcs(fm)
tmpl.Funcs(template.FuncMap{
"tpl": tplFunc(tmpl),
"tpl": tplFunc(tmpl),
"toYaml": toYamlFunc,
})
tplFunc(tmpl)
_, err := tmpl.Parse(tmplStr)
if err != nil {
return "", err
Expand Down
15 changes: 15 additions & 0 deletions pipeline/template_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,18 @@ func TestTemplateEngineRenderTplInvalid(t *testing.T) {
}, sprig.TxtFuncMap())
assert.Error(t, err)
}

func TestTemplateEngineRenderToYaml(t *testing.T) {
var (
out string
err error
)
out, err = renderTemplate("{{ toYaml . }}", map[string]interface{}{
"x": map[string]interface{}{
"z": "abc",
},
"y": 25,
}, sprig.TxtFuncMap())
assert.NoError(t, err)
assert.Equal(t, "x:\n z: abc\n\"y\": 25", out)
}

0 comments on commit 7f3fb0d

Please sign in to comment.