Skip to content

Commit 6635e95

Browse files
committed
issue-103: add keep_prefix option to load for preserving comments
- Add keep_prefix flag to lkml.load (default False) - Include raw preamble in output under _prefix when enabled - Add functional tests for with/without prefix
1 parent 5d76f6a commit 6635e95

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎docs/source/simple.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@ Fields that can be repeated (e.g. ``view``, ``dimension``, or ``join``) are comb
7070
{'name': 'amount', 'sql': '${TABLE}.amount'},
7171
{'name': 'status', 'sql': '${TABLE}.status'}]}
7272

73+
The ``keep_prefix`` parameter preserves leading comments and whitespace in a ``_prefix`` field.
74+
75+
.. doctest::
76+
77+
>>> result = lkml.load("# comment\ndimension: id {}", keep_prefix=True)
78+
>>> result['_prefix']
79+
'# comment\n'
80+
7381
Here's an example of some LookML that has been parsed into a dictionary. Note that the repeated key ``join`` has been transformed into a plural key ``joins``: a list of dictionaries representing each join::
7482

7583
{

‎lkml/__init__.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ def parse(text: str) -> DocumentNode:
3030
return tree
3131

3232

33-
def load(stream: Union[str, IO]) -> dict:
33+
def load(stream: Union[str, IO], keep_prefix: bool = False) -> dict:
3434
"""Parse LookML into a Python dictionary.
3535
3636
Args:
3737
stream: File object or string containing LookML to be parsed
38+
keep_prefix: If True, include the raw string of comments and whitespace
39+
at the top of the document under the "_prefix" key.
3840
3941
Raises:
4042
TypeError: If stream is neither a string or a file object
@@ -50,6 +52,8 @@ def load(stream: Union[str, IO]) -> dict:
5052
tree: DocumentNode = parse(text)
5153
visitor = DictVisitor()
5254
tree_as_dict: dict = visitor.visit(tree)
55+
if keep_prefix:
56+
tree_as_dict["_prefix"] = tree.prefix
5357
return tree_as_dict
5458

5559

‎tests/test_functional.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,13 @@ def test_repeated_dump_does_not_mutate_input():
120120
first = lkml.dump(parsed)
121121
second = lkml.dump(parsed)
122122
assert first == second
123+
124+
125+
def test_load_with_prefix():
126+
raw_text = (Path(__file__).parent / "resources" / "view_with_all_fields.view.lkml").read_text(encoding="utf-8")
127+
prefix = "# This is a comment\n# and another comment\n"
128+
raw_text = f"{prefix}{raw_text}"
129+
parsed = lkml.load(raw_text, keep_prefix=True)
130+
assert parsed["_prefix"] == prefix
131+
parsed_without_prefix = lkml.load(raw_text)
132+
assert "_prefix" not in parsed_without_prefix

0 commit comments

Comments
 (0)