Skip to content

Commit

Permalink
fix(formatter): Avoid rewriting the file if it has not been changed
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mitya57 committed Dec 6, 2023
1 parent 2761307 commit 6965ba5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/djlint/reformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
11 changes: 11 additions & 0 deletions tests/test_djlint/test_djlint.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@


# pylint: disable=C0116
from os.path import getmtime
from pathlib import Path
from typing import TextIO

Expand Down Expand Up @@ -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"<div>\n <p>nice stuff here</p>\n</div>\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:
Expand Down

0 comments on commit 6965ba5

Please sign in to comment.