Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pipeline: Add 'toYaml' function #49

Merged
merged 1 commit into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading