From 20294968548a5d25d50c980181c21eb9199890bf Mon Sep 17 00:00:00 2001 From: Christopher Pickering Date: Wed, 6 Oct 2021 15:41:21 +0200 Subject: [PATCH] simplified regex to improve speed --- src/djlint/formatter/compress_html.py | 39 ++------------------------- tests/test_django.py | 8 +++++- 2 files changed, 9 insertions(+), 38 deletions(-) diff --git a/src/djlint/formatter/compress_html.py b/src/djlint/formatter/compress_html.py index 2a6f059..65c1405 100644 --- a/src/djlint/formatter/compress_html.py +++ b/src/djlint/formatter/compress_html.py @@ -82,28 +82,10 @@ def compress_html(html: str, config: Config) -> str: html = _strip_html_whitespace(html, config) - html = re.sub( - r"(<([\w]+)[^>]*>)\s+?(<\/\2>)", - r"\1\3", - html, - flags=re.IGNORECASE | re.MULTILINE, - ) - - # put empty template tags on one line - html = re.sub( - re.compile( - rf"({{%-?[ ]*?({config.start_template_tags})[^}}]+?-?%}})\s+?(\{{\%-?[ ]end\2[^}}]*?\%\}})", - flags=re.MULTILINE | re.IGNORECASE | re.VERBOSE, - ), - r"\1\3", - html, - ) - # put short single line tags on one line - # verbose doesn't seem to work with replace groups. html = re.sub( re.compile( - fr"(<({config.single_line_html_tags})>)\s*([^<\n]{{,80}})\s*?()", + fr"(<({config.single_line_html_tags})(?:[^<>])*>)\s*([^<\n]{{,80}})\s*?()", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE, ), r"\1\3\4", @@ -111,24 +93,7 @@ def compress_html(html: str, config: Config) -> str: re.IGNORECASE | re.MULTILINE | re.DOTALL, ) - html = re.sub( - re.compile( - fr"(<({config.single_line_html_tags})>)\s*?([^<\n]{{,80}})\s*?()", - re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE, - ), - r"\1\3\4", - html, - ) - - html = re.sub( - re.compile( - fr"(<({config.single_line_html_tags})[ ][^>\n]{{,80}}>)\s*([^<\n]{{,80}})\s*?()", - re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE, - ), - r"\1\3\4", - html, - ) - + # put short template tags back on one line html = re.sub( re.compile( rf"({{%-?[ ]*?({config.single_line_template_tags})[^\n(?:%}})]{{,30}}%}})\s*([^%\n]{{,50}})\s*?({{%-?[ ]+?end(\2)[ ]*?%}})", diff --git a/tests/test_django.py b/tests/test_django.py index 7aaacd3..180c622 100644 --- a/tests/test_django.py +++ b/tests/test_django.py @@ -7,7 +7,7 @@ run:: for a single test, run:: - pytest tests/test_django.py::test_complex_attributes --cov=src/djlint \ + pytest tests/test_django.py::test_empty_tags_on_one_line --cov=src/djlint \ --cov-branch --cov-report xml:coverage.xml --cov-report term-missing """ @@ -20,6 +20,12 @@ from click.testing import CliRunner from .conftest import reformat +def test_empty_tags_on_one_line(runner: CliRunner, tmp_file: TextIO) -> None: + output = reformat(tmp_file, runner, b"{% if stuff %}\n{% endif %}") + assert output["text"] == """{% if stuff %}{% endif %}\n""" + assert output["exit_code"] == 1 + + def test_dj_comments_tag(runner: CliRunner, tmp_file: TextIO) -> None: output = reformat( tmp_file, runner, b"{# comment #}\n{% if this %}
{% endif %}"