From 6965ba57f8849e2a4f09d83ab01bdddb84c5ed2f Mon Sep 17 00:00:00 2001 From: Dmitry Shachnev Date: Wed, 6 Dec 2023 13:56:23 +0300 Subject: [PATCH] fix(formatter): Avoid rewriting the file if it has not been changed We use djLint as part of treefmt [1] to reformat HTML templates tree-wide, and treefmt looks at file modification time to determine if it was reformatted or not. And with --fail-on-change option passed, it exits with status 1 when it thinks files are modified. This patch makes djLint not rewrite the file if there are no changes to write back, which makes treefmt --fail-on-change do the right thing. [1]: https://github.com/numtide/treefmt --- src/djlint/reformat.py | 4 +++- tests/test_djlint/test_djlint.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/djlint/reformat.py b/src/djlint/reformat.py index cf9b27d6..99a2fa35 100644 --- a/src/djlint/reformat.py +++ b/src/djlint/reformat.py @@ -52,7 +52,9 @@ def reformat_file(config: Config, this_file: Path) -> dict: beautified_code = formatter(config, rawcode) - if config.check is not True or config.stdin is True: + if ( + config.check is not True and beautified_code != rawcode + ) or config.stdin is True: this_file.write_bytes(beautified_code.encode("utf8")) out = { diff --git a/tests/test_djlint/test_djlint.py b/tests/test_djlint/test_djlint.py index cbf5adfe..7a92da15 100644 --- a/tests/test_djlint/test_djlint.py +++ b/tests/test_djlint/test_djlint.py @@ -23,6 +23,7 @@ # pylint: disable=C0116 +from os.path import getmtime from pathlib import Path from typing import TextIO @@ -174,6 +175,16 @@ def test_reformatter_simple_error(runner: CliRunner, tmp_file: TextIO) -> None: assert "1 file was updated." in result.output +def test_reformatter_no_error(runner: CliRunner, tmp_file: TextIO) -> None: + write_to_file(tmp_file.name, b"
\n

nice stuff here

\n
\n") + old_mtime = getmtime(tmp_file.name) + result = runner.invoke(djlint, [tmp_file.name, "--reformat"]) + assert result.exit_code == 0 + assert "0 files were updated." in result.output + new_mtime = getmtime(tmp_file.name) + assert new_mtime == old_mtime + + def test_check_reformatter_simple_error_quiet( runner: CliRunner, tmp_file: TextIO ) -> None: