fix(js formatting): added support for jsbeautify ignore blocks

closes #367
This commit is contained in:
Christopher Pickering 2022-09-07 11:15:21 -05:00
parent 2d8948f288
commit b8bf071d16
No known key found for this signature in database
GPG key ID: E14DB3B0A0FACF84
5 changed files with 59 additions and 10 deletions

View file

@ -28,4 +28,7 @@ labels: [":microbe: bug", ":mag: linter"]
## How To Reproduce
<!-- Steps to reproduce the behavior -->
## Contents of .djlintrc/pyproject.toml [tool.djlint]
<!-- please include your config -->
<!-- Thanks! 🤠 -->

View file

@ -69,3 +69,6 @@ disable = "E1120, R0914, E0401, R0912, R0916, R0913, W0104, R0801, W1404, R0902,
[tool.pylint.TYPECHECK]
ignored-modules = "regex"
[tool.djlint]
format_js = true

View file

@ -18,15 +18,40 @@ def format_js(html: str, config: Config) -> str:
indent = len(match.group(1)) * " "
inner_indent = indent + config.indent
opts = BeautifierOptions(config.js_config)
beautified = (
"\n"
+ inner_indent
+ ("\n" + inner_indent).join(
jsbeautifier.beautify(match.group(3), opts).splitlines()
)
)
beautified_lines = jsbeautifier.beautify(match.group(3), opts).splitlines()
beautified = ""
# add indent back
ignore_indent = False
for line in beautified_lines:
if re.search(
re.compile(
r"\/\*[ ]*?beautify[ ]+?preserve:end[ ]*?\*\/",
re.DOTALL | re.IGNORECASE | re.MULTILINE,
),
line,
):
line = line.lstrip()
ignore_indent = False
if ignore_indent is False:
beautified += "\n" + inner_indent + line
else:
beautified += "\n" + line
if re.search(
re.compile(
r"\/\*[ ]*?beautify[ ]+?preserve:start[ ]*?\*\/",
re.DOTALL | re.IGNORECASE | re.MULTILINE,
),
line,
):
ignore_indent = True
return match.group(1) + match.group(2) + beautified + "\n" + indent

View file

@ -0,0 +1,8 @@
<script>
/* beautify preserve:start */
function(){}
function(){}
function(){}
/* beautify preserve:end */
</script>

View file

@ -2,10 +2,10 @@
run::
pytest tests/test_config/test_json/test_config.py --cov=src/djlint --cov-branch \
pytest tests/test_config/test_scripts_styles/test_config.py --cov=src/djlint --cov-branch \
--cov-report xml:coverage.xml --cov-report term-missing
pytest tests/test_config/test_json/test_config.py::test_config
pytest tests/test_config/test_scripts_styles/test_config.py::test_ignore
"""
# pylint: disable=C0116
@ -23,5 +23,15 @@ def test_config(runner: CliRunner) -> None:
"--check",
],
)
print(result.output)
assert result.exit_code == 0
def test_ignore(runner: CliRunner) -> None:
result = runner.invoke(
djlint,
[
"tests/test_config/test_scripts_styles/ignore.html",
"--check",
],
)
assert result.exit_code == 0