feat(tiller): add fromYaml to template functions

This adds a fromYaml template function.

Closes #1604
parent 736d9f8c
...@@ -174,3 +174,18 @@ func ToYaml(v interface{}) string { ...@@ -174,3 +174,18 @@ func ToYaml(v interface{}) string {
} }
return string(data) return string(data)
} }
// FromYaml converts a YAML document into a map[string]interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid
// YAML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["error"] in the returned map.
func FromYaml(str string) map[string]interface{} {
m := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}
...@@ -110,3 +110,34 @@ func TestToYaml(t *testing.T) { ...@@ -110,3 +110,34 @@ func TestToYaml(t *testing.T) {
t.Errorf("Expected %q, got %q", expect, got) t.Errorf("Expected %q, got %q", expect, got)
} }
} }
func TestFromYaml(t *testing.T) {
doc := `hello: world
one:
two: three
`
dict := FromYaml(doc)
if err, ok := dict["Error"]; ok {
t.Fatalf("Parse error: %s", err)
}
if len(dict) != 2 {
t.Fatal("expected two elements.")
}
world := dict["hello"]
if world.(string) != "world" {
t.Fatal("Expected the world. Is that too much to ask?")
}
// This should fail because we don't currently support lists:
doc2 := `
- one
- two
- three
`
dict = FromYaml(doc2)
if _, ok := dict["Error"]; !ok {
t.Fatal("Expected parser error")
}
}
...@@ -71,6 +71,7 @@ func FuncMap() template.FuncMap { ...@@ -71,6 +71,7 @@ func FuncMap() template.FuncMap {
// Add some extra functionality // Add some extra functionality
extra := template.FuncMap{ extra := template.FuncMap{
"toYaml": chartutil.ToYaml, "toYaml": chartutil.ToYaml,
"fromYaml": chartutil.FromYaml,
// This is a placeholder for the "include" function, which is // This is a placeholder for the "include" function, which is
// late-bound to a template. By declaring it here, we preserve the // late-bound to a template. By declaring it here, we preserve the
......
...@@ -49,7 +49,7 @@ func TestFuncMap(t *testing.T) { ...@@ -49,7 +49,7 @@ func TestFuncMap(t *testing.T) {
} }
// Test for Engine-specific template functions. // Test for Engine-specific template functions.
expect := []string{"include", "toYaml"} expect := []string{"include", "toYaml", "fromYaml"}
for _, f := range expect { for _, f := range expect {
if _, ok := fns[f]; !ok { if _, ok := fns[f]; !ok {
t.Errorf("Expected add-on function %q", f) t.Errorf("Expected add-on function %q", f)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment