Meta information for objects and not just for blocks?
ioah86 opened this issue · comments
Albert Heinle commented
I love the feature where you include line numbers to blocks. Why was this not extended to objecs?
python-hcl2/hcl2/transformer.py
Lines 100 to 105 in 252ebaf
I tried out a small alteration, and it seems to work fine for me:
class CustomDictTransformer(hcl2.transformer.DictTransformer):
"""
Custom alteration of the DictTransformer.
"""
@v_args(meta=True)
def object(self, meta: Meta, args: List) -> Dict:
args = self.strip_new_line_tokens(args)
result: Dict[str, Any] = {}
for arg in args:
result.update(arg)
if self.with_meta:
result.update(
{
hcl2.transformer.START_LINE: meta.line,
hcl2.transformer.END_LINE: meta.end_line,
}
)
return result
def load_hcl2(file: TextIO, with_meta=False) -> dict:
"""Load a HCL2 file.
:param file: File with hcl2 to be loaded as a dict.
:param with_meta: If set to true then adds `__start_line__` and `__end_line__`
parameters to the output dict. Default to false.
"""
return loads_hcl2(file.read(), with_meta=with_meta)
def loads_hcl2(text: str, with_meta=False) -> dict:
"""Load HCL2 from a string.
:param text: Text with hcl2 to be loaded as a dict.
:param with_meta: If set to true then adds `__start_line__` and `__end_line__`
parameters to the output dict. Default to false.
"""
# append new line as a workaround for https://github.com/lark-parser/lark/issues/237
# Lark doesn't support a EOF token so our grammar can't look for "new line or end of file"
# This means that all blocks must end in a new line even if the file ends
# Append a new line as a temporary fix
tree = hcl2.parser.hcl2.parse(text + "\n")
return CustomDictTransformer(with_meta=with_meta).transform(tree)
I would suggest to add that. It does not hurt and is useful for the people using meta information.