Skip to content

Commit

Permalink
Properly handle escapes within HCL strings (closes amplify-education#171
Browse files Browse the repository at this point in the history
)
  • Loading branch information
weaversam8 committed Oct 24, 2024
1 parent 23c63c3 commit 373aa78
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
20 changes: 18 additions & 2 deletions hcl2/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,15 +281,31 @@ def to_string_dollar(self, value: Any) -> Any:
"""Wrap a string in ${ and }"""
if isinstance(value, str):
if value.startswith('"') and value.endswith('"'):
return str(value)[1:-1]
value = str(value)[1:-1]
return self.process_escape_sequences(value)
return f"${{{value}}}"
return value

def strip_quotes(self, value: Any) -> Any:
"""Remove quote characters from the start and end of a string"""
if isinstance(value, str):
if value.startswith('"') and value.endswith('"'):
return str(value)[1:-1]
value = str(value)[1:-1]
return self.process_escape_sequences(value)
return value

def process_escape_sequences(self, value: str) -> str:
"""Process HCL escape sequences within quoted template expressions."""
if isinstance(value, str):
# normal escape sequences
value = value.replace("\\n", "\n")
value = value.replace("\\r", "\r")
value = value.replace("\\t", "\t")
value = value.replace('\\"', '"')
value = value.replace("\\\\", "\\")

# we will leave Unicode escapes (\uNNNN and \UNNNNNNNN) untouched
# for now, but this method can be extended in the future
return value

def identifier(self, value: Any) -> Any:
Expand Down
9 changes: 9 additions & 0 deletions test/helpers/terraform-config-json/escapes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"block": [
{
"block_with_newlines": {
"a": "line1\nline2"
}
}
]
}
3 changes: 3 additions & 0 deletions test/helpers/terraform-config/escapes.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
block "block_with_newlines" {
a = "line1\nline2"
}

0 comments on commit 373aa78

Please sign in to comment.