Commit 090e00dd authored by Matt Butcher's avatar Matt Butcher Committed by GitHub

Merge pull request #1686 from kubernetes/feat/1604-fromyaml

feat(tiller): add fromYaml to template functions
parents 16330853 d8540d78
......@@ -174,3 +174,18 @@ func ToYaml(v interface{}) string {
}
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) {
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")
}
}
......@@ -70,7 +70,8 @@ func FuncMap() template.FuncMap {
// Add some extra functionality
extra := template.FuncMap{
"toYaml": chartutil.ToYaml,
"toYaml": chartutil.ToYaml,
"fromYaml": chartutil.FromYaml,
// This is a placeholder for the "include" function, which is
// late-bound to a template. By declaring it here, we preserve the
......
......@@ -49,7 +49,7 @@ func TestFuncMap(t *testing.T) {
}
// Test for Engine-specific template functions.
expect := []string{"include", "toYaml"}
expect := []string{"include", "toYaml", "fromYaml"}
for _, f := range expect {
if _, ok := fns[f]; !ok {
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