From 3d7ae42df476e72b87ef0922f638ece34cd3b1b1 Mon Sep 17 00:00:00 2001 From: Sam Weaver Date: Fri, 11 Oct 2024 11:44:30 -0400 Subject: [PATCH] Fix block labels and booleans during reconstruction --- hcl2/reconstructor.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/hcl2/reconstructor.py b/hcl2/reconstructor.py index 19f7510..fb3e1c0 100644 --- a/hcl2/reconstructor.py +++ b/hcl2/reconstructor.py @@ -202,8 +202,13 @@ def _NL(self, level: int, comma: bool = False) -> Tree: # rules: the value of a block is always an array of dicts, # the key is the block type def _list_is_a_block(self, v: list) -> bool: - sub_obj = v[0] + for obj in v: + if not self._dict_is_a_block(obj): + return False + return True + + def _dict_is_a_block(self, sub_obj: any) -> bool: # if the list doesn't contain dictionaries, it's not a block if not isinstance(sub_obj, dict): return False @@ -223,7 +228,7 @@ def _list_is_a_block(self, v: list) -> bool: # object is a block (recurse) label = list(sub_obj)[0] sub_sub_obj = sub_obj[label] - if self._list_is_a_block([sub_sub_obj]): + if self._dict_is_a_block(sub_sub_obj): return True # if the objects in the array have a single key whose child is not a @@ -234,6 +239,11 @@ def _block_has_label(self, b: dict) -> bool: return len(b.keys()) == 1 def _calculate_block_labels(self, b: dict) -> List[str]: + # if b doesn't have a label + if len(b.keys()) != 1: + return ([], b) + + # otherwise, find the label curr_label = list(b)[0] potential_body = b[curr_label] if ( @@ -351,6 +361,17 @@ def _transform_value_to_expr_term(self, v, level) -> Token: return Tree( Token("RULE", "expr_term"), [Tree(Token("RULE", "object"), elems)] ) + # treat booleans appropriately + elif isinstance(v, bool): + return Tree( + Token("RULE", "expr_term"), + [ + Tree( + Token("RULE", "identifier"), + [Token("NAME", "true" if v else "false")], + ) + ], + ) # store integers as literals, digit by digit elif isinstance(v, int): return Tree(