From 77ba054a11b1942fa4f4483e073a29146b5ce18d Mon Sep 17 00:00:00 2001 From: Jack Zampolin Date: Tue, 28 Feb 2017 17:01:03 -0800 Subject: [PATCH] Add toToml template function --- pkg/chartutil/files.go | 14 ++++++++++++++ pkg/chartutil/files_test.go | 13 +++++++++++++ pkg/engine/engine.go | 1 + pkg/engine/engine_test.go | 2 +- 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/pkg/chartutil/files.go b/pkg/chartutil/files.go index 516a83fd2..e336eb066 100644 --- a/pkg/chartutil/files.go +++ b/pkg/chartutil/files.go @@ -25,6 +25,7 @@ import ( "github.com/gobwas/glob" "github.com/golang/protobuf/ptypes/any" + "github.com/naoina/toml" ) // Files is a map of files in a chart that can be accessed from a template. @@ -191,6 +192,19 @@ func FromYaml(str string) map[string]interface{} { return m } +// ToToml takes an interface, marshals it to yaml, and returns a string. It will +// always return a string, even on marshal error (empty string). +// +// This is designed to be called from a template. +func ToToml(v interface{}) string { + data, err := toml.Marshall(v) + if err != nil { + // Swallow error inside of a template. + return "" + } + return string(data) +} + // ToJson takes an interface, marshals it to json, and returns a string. It will // always return a string, even on marshal error (empty string). // diff --git a/pkg/chartutil/files_test.go b/pkg/chartutil/files_test.go index c522e0078..c54af4b96 100644 --- a/pkg/chartutil/files_test.go +++ b/pkg/chartutil/files_test.go @@ -111,6 +111,19 @@ func TestToYaml(t *testing.T) { } } +func TestToToml(t *testing) { + expect := "foo = bar\n" + v := struct { + Foo string `json:"foo"` + }{ + Foo: "bar", + } + + if got := ToToml(v); got != expect { + t.Errorf("Expected %q, got %q", expect, got) + } +} + func TestFromYaml(t *testing.T) { doc := `hello: world one: diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index 88a661865..95831ad40 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -70,6 +70,7 @@ func FuncMap() template.FuncMap { // Add some extra functionality extra := template.FuncMap{ + "toToml": chartutil.ToToml, "toYaml": chartutil.ToYaml, "fromYaml": chartutil.FromYaml, "toJson": chartutil.ToJson, diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.go index e202804da..60f708eec 100644 --- a/pkg/engine/engine_test.go +++ b/pkg/engine/engine_test.go @@ -49,7 +49,7 @@ func TestFuncMap(t *testing.T) { } // Test for Engine-specific template functions. - expect := []string{"include", "toYaml", "fromYaml"} + expect := []string{"include", "toYaml", "fromYaml", "toJson", "fromJson", "toToml"} for _, f := range expect { if _, ok := fns[f]; !ok { t.Errorf("Expected add-on function %q", f)