From fbda5b119a68d091431ed06098b1fc83caaebd16 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 21 May 2015 13:40:33 -0600 Subject: [PATCH] template: variable parsing --- template/parse.go | 20 ++++++++++++++++ template/parse_test.go | 24 +++++++++++++++++++ .../test-fixtures/parse-variable-default.json | 5 ++++ .../parse-variable-required.json | 5 ++++ 4 files changed, 54 insertions(+) create mode 100644 template/test-fixtures/parse-variable-default.json create mode 100644 template/test-fixtures/parse-variable-required.json diff --git a/template/parse.go b/template/parse.go index a96117111..47d97effa 100644 --- a/template/parse.go +++ b/template/parse.go @@ -30,6 +30,26 @@ func (r *rawTemplate) Template() (*Template, error) { var result Template var errs error + // Gather the variables + if len(r.Variables) > 0 { + result.Variables = make(map[string]*Variable, len(r.Variables)) + } + for k, rawV := range r.Variables { + var v Variable + + // Variable is required if the value is exactly nil + v.Required = rawV == nil + + // Weak decode the default if we have one + if err := r.decoder(&v.Default, nil).Decode(rawV); err != nil { + errs = multierror.Append(errs, fmt.Errorf( + "variable %s: %s", k, err)) + continue + } + + result.Variables[k] = &v + } + // Let's start by gathering all the builders if len(r.Builders) > 0 { result.Builders = make(map[string]*Builder, len(r.Builders)) diff --git a/template/parse_test.go b/template/parse_test.go index 2c5b8f735..fcf7fcf29 100644 --- a/template/parse_test.go +++ b/template/parse_test.go @@ -117,6 +117,30 @@ func TestParse(t *testing.T) { nil, true, }, + + { + "parse-variable-default.json", + &Template{ + Variables: map[string]*Variable{ + "foo": &Variable{ + Default: "foo", + }, + }, + }, + false, + }, + + { + "parse-variable-required.json", + &Template{ + Variables: map[string]*Variable{ + "foo": &Variable{ + Required: true, + }, + }, + }, + false, + }, } for _, tc := range cases { diff --git a/template/test-fixtures/parse-variable-default.json b/template/test-fixtures/parse-variable-default.json new file mode 100644 index 000000000..05192b64d --- /dev/null +++ b/template/test-fixtures/parse-variable-default.json @@ -0,0 +1,5 @@ +{ + "variables": { + "foo": "foo" + } +} diff --git a/template/test-fixtures/parse-variable-required.json b/template/test-fixtures/parse-variable-required.json new file mode 100644 index 000000000..ca6458aaa --- /dev/null +++ b/template/test-fixtures/parse-variable-required.json @@ -0,0 +1,5 @@ +{ + "variables": { + "foo": null + } +}