From f65d314d583b9705e37c7ba7a63a5fa0e2e0588c Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 21 Aug 2014 14:38:45 -0700 Subject: [PATCH] hcl: support variable interpolations for compat with libucl --- decoder_test.go | 1 + hcl/lex.go | 19 ++++++++++++++++++- json/lex.go | 5 +++++ test-fixtures/basic.hcl | 1 + test-fixtures/basic.json | 3 ++- 5 files changed, 27 insertions(+), 2 deletions(-) diff --git a/decoder_test.go b/decoder_test.go index 1a8abcf..75980ff 100644 --- a/decoder_test.go +++ b/decoder_test.go @@ -18,6 +18,7 @@ func TestDecode_interface(t *testing.T) { false, map[string]interface{}{ "foo": "bar", + "bar": "${file(\"bing/bong.txt\")}", }, }, { diff --git a/hcl/lex.go b/hcl/lex.go index 4d4154d..ba1d6f7 100644 --- a/hcl/lex.go +++ b/hcl/lex.go @@ -224,6 +224,8 @@ func (x *hclLex) lexNumber(yylval *hclSymType) int { // lexString extracts a string from the input func (x *hclLex) lexString(yylval *hclSymType) int { + braces := 0 + var b bytes.Buffer for { c := x.next() @@ -232,10 +234,25 @@ func (x *hclLex) lexString(yylval *hclSymType) int { } // String end - if c == '"' { + if c == '"' && braces == 0 { break } + // If we're starting into variable, mark it + if braces == 0 && c == '$' && x.peek() == '{' { + braces += 1 + + if _, err := b.WriteRune(c); err != nil { + return lexEOF + } + c = x.next() + } else if braces > 0 && c == '{' { + braces += 1 + } + if braces > 0 && c == '}' { + braces -= 1 + } + if _, err := b.WriteRune(c); err != nil { return lexEOF } diff --git a/json/lex.go b/json/lex.go index 3ddce6f..0601ec1 100644 --- a/json/lex.go +++ b/json/lex.go @@ -125,6 +125,11 @@ func (x *jsonLex) lexString(yylval *jsonSymType) int { break } + // If we're escaping a quote, then escape the quote + if c == '\\' && x.peek() == '"' { + c = x.next() + } + if _, err := b.WriteRune(c); err != nil { return lexEOF } diff --git a/test-fixtures/basic.hcl b/test-fixtures/basic.hcl index 05c8891..9499944 100644 --- a/test-fixtures/basic.hcl +++ b/test-fixtures/basic.hcl @@ -1 +1,2 @@ foo = "bar" +bar = "${file("bing/bong.txt")}" diff --git a/test-fixtures/basic.json b/test-fixtures/basic.json index b54bde9..7bdddc8 100644 --- a/test-fixtures/basic.json +++ b/test-fixtures/basic.json @@ -1,3 +1,4 @@ { - "foo": "bar" + "foo": "bar", + "bar": "${file(\"bing/bong.txt\")}" }