From 9092278d155684f5268202eae87f80926047ba45 Mon Sep 17 00:00:00 2001 From: i071873 Date: Sun, 11 Jun 2023 11:25:10 +0200 Subject: [PATCH] Adding support to customize helm template funcs Signed-off-by: Alex Volchok --- pkg/engine/engine.go | 9 +++++++++ pkg/engine/engine_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index 657d5767b..8bf3d6b41 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -44,6 +44,11 @@ type Engine struct { config *rest.Config // EnableDNS tells the engine to allow DNS lookups when rendering templates EnableDNS bool + // WithCustomFuncs allows you to provide a template.FuncMap containing custom template functions to be added or + // overridden. It is typically used as a configuration option to extend the default set of template functions with + // custom ones. The provided template.FuncMap can extend the default template functions, and the resulting + // FuncMap is used by the template engine. + WithCustomFuncs func(funcs template.FuncMap) template.FuncMap } // New creates a new instance of Engine using the passed in rest config. @@ -206,6 +211,10 @@ func (e Engine) initFunMap(t *template.Template, referenceTpls map[string]render } } + if e.WithCustomFuncs != nil { + funcMap = e.WithCustomFuncs(funcMap) + } + t.Funcs(funcMap) } diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.go index 434b939dc..a2dc25d2a 100644 --- a/pkg/engine/engine_test.go +++ b/pkg/engine/engine_test.go @@ -22,6 +22,7 @@ import ( "strings" "sync" "testing" + "text/template" "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chartutil" @@ -727,6 +728,44 @@ func TestAlterFuncMap_require(t *testing.T) { } } +func TestWithCustomFuncMap_tpl(t *testing.T) { + c := &chart.Chart{ + Metadata: &chart.Metadata{Name: "TplFunction"}, + Templates: []*chart.File{ + {Name: "templates/base", Data: []byte(`Evaluate tpl {{tpl "Value: {{ .Values.value | custom }}" .}}`)}, + }, + } + + v := chartutil.Values{ + "Values": chartutil.Values{ + "value": "myvalue", + }, + "Chart": c.Metadata, + "Release": chartutil.Values{ + "Name": "TestRelease", + }, + } + + e := Engine{ + WithCustomFuncs: func(funcs template.FuncMap) template.FuncMap { + funcs["custom"] = func(name string) string { + return fmt.Sprintf("%s-from-custom-func", name) + } + return funcs + }, + } + + out, err := e.Render(c, v) + if err != nil { + t.Fatal(err) + } + + expect := "Evaluate tpl Value: myvalue-from-custom-func" + if got := out["TplFunction/templates/base"]; got != expect { + t.Errorf("Expected %q, got %q (%v)", expect, got, out) + } +} + func TestAlterFuncMap_tpl(t *testing.T) { c := &chart.Chart{ Metadata: &chart.Metadata{Name: "TplFunction"},