From facbb6577d060cd841c9c761d5e7320539640743 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sat, 13 Jun 2015 16:19:25 -0400 Subject: [PATCH] template: allow _ prefix to root level keys for comments [GH-2066] --- template/parse.go | 9 +++++++-- template/parse_test.go | 13 +++++++++++++ template/test-fixtures/parse-comment.json | 4 ++++ .../docs/templates/introduction.html.markdown | 16 ++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 template/test-fixtures/parse-comment.json diff --git a/template/parse.go b/template/parse.go index dbb29569d..f64057db2 100644 --- a/template/parse.go +++ b/template/parse.go @@ -291,11 +291,16 @@ func Parse(r io.Reader) (*Template, error) { if len(md.Unused) > 0 { sort.Strings(md.Unused) for _, unused := range md.Unused { + // Ignore keys starting with '_' as comments + if unused[0] == '_' { + continue + } + err = multierror.Append(err, fmt.Errorf( "Unknown root level key in template: '%s'", unused)) } - - // Return early for these errors + } + if err != nil { return nil, err } diff --git a/template/parse_test.go b/template/parse_test.go index 9abca2f77..5285e27d3 100644 --- a/template/parse_test.go +++ b/template/parse_test.go @@ -303,6 +303,19 @@ func TestParse(t *testing.T) { }, false, }, + + { + "parse-comment.json", + &Template{ + Builders: map[string]*Builder{ + "something": &Builder{ + Name: "something", + Type: "something", + }, + }, + }, + false, + }, } for _, tc := range cases { diff --git a/template/test-fixtures/parse-comment.json b/template/test-fixtures/parse-comment.json new file mode 100644 index 000000000..d3bb95a3b --- /dev/null +++ b/template/test-fixtures/parse-comment.json @@ -0,0 +1,4 @@ +{ + "_info": "foo", + "builders": [{"type": "something"}] +} diff --git a/website/source/docs/templates/introduction.html.markdown b/website/source/docs/templates/introduction.html.markdown index a8be4f592..3dc363916 100644 --- a/website/source/docs/templates/introduction.html.markdown +++ b/website/source/docs/templates/introduction.html.markdown @@ -58,6 +58,22 @@ Along with each key, it is noted whether it is required or not. For more information on how to define and use user variables, read the sub-section on [user variables in templates](/docs/templates/user-variables.html). +## Comments + +JSON doesn't support comments and Packer reports unknown keys as validation +errors. If you'd like to comment your template, you can prefix a _root level_ +key with an underscore. Example: + +```javascript +{ + "_comment": "This is a comment", + "builders": [{}] +} +``` + +**Important:** Only _root level_ keys can be underscore prefixed. Keys within +builders, provisioners, etc. will still result in validation errors. + ## Example Template Below is an example of a basic template that is nearly fully functional. It is just