Skip to content

Commit

Permalink
Fix minifying strings-in-containers as if they were docstrings.
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh committed Aug 18, 2024
1 parent 307fc3c commit 5e68403
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
12 changes: 11 additions & 1 deletion belay/_minify.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def minify(code: str) -> str:
level = 0
global_start_col = 0
prev_token_types = deque([INDENT], maxlen=2)
container_level = 0

for (
token_type,
Expand All @@ -60,8 +61,17 @@ def minify(code: str) -> str:
continue
elif token_type == COMMENT:
continue
elif token_type == OP:
if string in "([{":
container_level += 1
elif string in ")]}":
container_level = max(0, container_level - 1)

if token_type == STRING and (prev_token_type in (NEWLINE, INDENT) or start_col == global_start_col):
if (
token_type == STRING
and container_level == 0
and (prev_token_type in (NEWLINE, INDENT) or start_col == global_start_col)
):
# Docstring
out.append(" " * level + "0" + "\n" * string.count("\n"))
elif start_line > prev_start_line and token_type != NEWLINE:
Expand Down
47 changes: 47 additions & 0 deletions tests/test_minify.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,50 @@ def test_minify_ops():
return "test test"
"""
assert res == expected


def test_minify_newline_pass_0():
"""Replicated issue https://github.com/BrianPugh/belay/issues/167."""
res = minify(
"""
print(src_code)
l1 =[
'foo','bar']
l2 =['foo','bar']
l3 =['foo',
'bar']
l4 =['foo',
'bar',
'baz']
l5 =[
'foo','foo',
'bar','bar',
'baz','baz']
print ('l1',l1 )
print ('l2',l2 )
print ('l3',l3 )
print ('l4',l4 )
print ('l5',l5 )
"""
)
expected = """
print(src_code)
l1=[
'foo','bar']
l2=['foo','bar']
l3=['foo',
'bar']
l4=['foo',
'bar',
'baz']
l5=[
'foo','foo',
'bar','bar',
'baz','baz']
print('l1',l1)
print('l2',l2)
print('l3',l3)
print('l4',l4)
print('l5',l5)
"""
assert res == expected

0 comments on commit 5e68403

Please sign in to comment.