From 5e684034082b8d2b96810f08c700060b738bfe87 Mon Sep 17 00:00:00 2001 From: Brian Pugh Date: Sun, 18 Aug 2024 09:37:31 -0400 Subject: [PATCH] Fix minifying strings-in-containers as if they were docstrings. --- belay/_minify.py | 12 ++++++++++- tests/test_minify.py | 47 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/belay/_minify.py b/belay/_minify.py index 90443c7..e0129f1 100644 --- a/belay/_minify.py +++ b/belay/_minify.py @@ -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, @@ -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: diff --git a/tests/test_minify.py b/tests/test_minify.py index 34e3d99..cda36b5 100644 --- a/tests/test_minify.py +++ b/tests/test_minify.py @@ -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