Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Meta information for objects and not just for blocks? #130

Open
ioah86 opened this issue Apr 28, 2023 · 0 comments
Open

Meta information for objects and not just for blocks? #130

ioah86 opened this issue Apr 28, 2023 · 0 comments

Comments

@ioah86
Copy link

ioah86 commented Apr 28, 2023

I love the feature where you include line numbers to blocks. Why was this not extended to objecs?

def object(self, args: List) -> Dict:
args = self.strip_new_line_tokens(args)
result: Dict[str, Any] = {}
for arg in args:
result.update(arg)
return result

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant