From 7c0a2721504d489b92dbd252d42f4eea7744844b Mon Sep 17 00:00:00 2001 From: Christopher Pickering Date: Thu, 19 Jan 2023 08:30:31 -0600 Subject: [PATCH] fix(formatter): preserve windows line endings Line ending from first line will now be preserved in the output. closes #502 --- src/djlint/__init__.py | 1 - src/djlint/reformat.py | 9 +++++++-- tests/test_djlint/test_djlint.py | 15 +++++++++++++++ windows.html | 1 + 4 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 windows.html diff --git a/src/djlint/__init__.py b/src/djlint/__init__.py index 978401c..3c10356 100644 --- a/src/djlint/__init__.py +++ b/src/djlint/__init__.py @@ -180,7 +180,6 @@ def main( config.stdin = True stdin_stream = click.get_text_stream("stdin", encoding="utf8") stdin_text = stdin_stream.read() - temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.write(str.encode(stdin_text)) temp_file.seek(0) diff --git a/src/djlint/reformat.py b/src/djlint/reformat.py index 5d01dbc..47f8569 100644 --- a/src/djlint/reformat.py +++ b/src/djlint/reformat.py @@ -17,7 +17,7 @@ from .settings import Config def reformat_file(config: Config, this_file: Path) -> dict: """Reformat html file.""" - rawcode = this_file.read_text(encoding="utf8") + rawcode = this_file.read_bytes().decode("utf8") compressed = compress_html(rawcode, config) @@ -33,9 +33,14 @@ def reformat_file(config: Config, this_file: Path) -> dict: if config.format_js: beautified_code = format_js(beautified_code, config) + # preserve original line endings + line_ending = rawcode.find("\n") + if line_ending > -1 and rawcode[max(line_ending - 1, 0)] == "\r": + beautified_code = beautified_code.replace("\n", "\r\n") + if config.check is not True or config.stdin is True: # update the file - this_file.write_text(beautified_code, encoding="utf8") + this_file.write_text(beautified_code, encoding="utf8", newline="") out = { str(this_file): list( diff --git a/tests/test_djlint/test_djlint.py b/tests/test_djlint/test_djlint.py index 2bb5f5a..251713c 100644 --- a/tests/test_djlint/test_djlint.py +++ b/tests/test_djlint/test_djlint.py @@ -222,3 +222,18 @@ def test_python_call() -> None: ) assert b"python -m djlint [OPTIONS] SRC ..." in py_sub.stdout assert py_sub.returncode == 0 + + +def test_line_ending(runner: CliRunner, tmp_file: TextIO) -> None: + # write a windows line ending to file + text_in = "
\r\n" + with open(tmp_file.name, "w", encoding="utf8", newline="") as windows: + windows.write(text_in) + + # make sure line ending was still there + assert Path(tmp_file.name).read_bytes().decode("utf8") == text_in + + # check formatting + result = runner.invoke(djlint, [tmp_file.name, "--check", "--quiet"]) + + assert result.exit_code == 0 diff --git a/windows.html b/windows.html new file mode 100644 index 0000000..b6ea759 --- /dev/null +++ b/windows.html @@ -0,0 +1 @@ +