From 431cc46cad3ae5248e32df1f6c44f2f4ce5547ba Mon Sep 17 00:00:00 2001
From: Matt Butcher <mbutcher@engineyard.com>
Date: Mon, 26 Sep 2016 14:33:54 -0600
Subject: [PATCH] feat(tiller): add toYaml template function

This adds the function toYaml to the Engine template functions.

Closes #1225
---
 pkg/engine/engine.go      | 14 ++++++++++++++
 pkg/engine/engine_test.go | 13 +++++++++++++
 2 files changed, 27 insertions(+)

diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go
index e415913a3..93927bcb5 100644
--- a/pkg/engine/engine.go
+++ b/pkg/engine/engine.go
@@ -24,6 +24,8 @@ import (
 	"text/template"
 
 	"github.com/Masterminds/sprig"
+	"github.com/ghodss/yaml"
+
 	"k8s.io/helm/pkg/chartutil"
 	"k8s.io/helm/pkg/proto/hapi/chart"
 )
@@ -49,11 +51,23 @@ func New() *Engine {
 	f := sprig.TxtFuncMap()
 	delete(f, "env")
 	delete(f, "expandenv")
+
+	// Add a function to convert to YAML:
+	f["toYaml"] = toYaml
 	return &Engine{
 		FuncMap: f,
 	}
 }
 
+func toYaml(v interface{}) string {
+	data, err := yaml.Marshal(v)
+	if err != nil {
+		// Swallow errors inside of a template.
+		return ""
+	}
+	return string(data)
+}
+
 // Render takes a chart, optional values, and value overrides, and attempts to render the Go templates.
 //
 // Render can be called repeatedly on the same engine.
diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.go
index ef71bbd0c..d9e595412 100644
--- a/pkg/engine/engine_test.go
+++ b/pkg/engine/engine_test.go
@@ -27,6 +27,19 @@ import (
 	"github.com/golang/protobuf/ptypes/any"
 )
 
+func TestToYaml(t *testing.T) {
+	expect := "foo: bar\n"
+	v := struct {
+		Foo string `json:"foo"`
+	}{
+		Foo: "bar",
+	}
+
+	if got := toYaml(v); got != expect {
+		t.Errorf("Expected %q, got %q", expect, got)
+	}
+}
+
 func TestEngine(t *testing.T) {
 	e := New()
 
-- 
GitLab