Skip to content

Commit

Permalink
fix: catch syntax errors in ast parse
Browse files Browse the repository at this point in the history
  • Loading branch information
tconbeer committed Dec 17, 2023
1 parent 94c772a commit df46805
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
10 changes: 6 additions & 4 deletions src/sqlfmt/jinjafmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,12 @@ def _basic_str(self) -> str:
return f"{self.opening_marker} {self.verb}{self.code} {self.closing_marker}"

def _find_multiline_python_str_lines(self) -> MutableSet[int]:
# we don't have to worry about syntax errors here because black has already
# run on this code.
tree = ast.parse(self.code, mode="eval")

try:
tree = ast.parse(self.code, mode="eval")
except SyntaxError:
# this jinja isn't quite python, so give up here.
return set()

line_indicies: MutableSet[int] = set()
for node in ast.walk(tree):
if (
Expand Down
11 changes: 7 additions & 4 deletions tests/unit_tests/test_jinjafmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,15 +482,18 @@ def test_preprocess_and_postprocess_are_inverse_ops(source_string: str) -> None:
*BlackWrapper._preprocess_string(source_string)
).replace(" ", "") == source_string.replace(" ", "")


@pytest.mark.parametrize(
"source_string",
[
"""{{\n config(\n foo="bar",\n )\n}}""",
'''{{\n config(\n foo="""\n\nbar\n\n""",\n )\n}}''',
]
"""{{\n config(\n foo="bar",\n )\n}}""",
'''{{\n config(\n foo="""\n\nbar\n\n""",\n )\n}}''',
],
)
def test_multiline_str(source_string: str) -> None:
tag = JinjaTag.from_string(source_string=source_string, depth=(0, 0))
tag.code, tag.is_blackened = BlackWrapper().format_string(source_string=tag.code, max_length=88)
tag.code, tag.is_blackened = BlackWrapper().format_string(
source_string=tag.code, max_length=88
)
assert tag.is_blackened
assert str(tag) == source_string

0 comments on commit df46805

Please sign in to comment.