Skip to content

Commit

Permalink
fix(formatter): preserve windows line endings
Browse files Browse the repository at this point in the history
Line ending from first line will now be preserved in the output.

closes #502
  • Loading branch information
christopherpickering committed Jan 19, 2023
1 parent ec7a7f0 commit 7c0a272
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
1 change: 0 additions & 1 deletion src/djlint/__init__.py
Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions src/djlint/reformat.py
Expand Up @@ -17,7 +17,7 @@

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)

Expand All @@ -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(
Expand Down
15 changes: 15 additions & 0 deletions tests/test_djlint/test_djlint.py
Expand Up @@ -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 = "<div></div>\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
1 change: 1 addition & 0 deletions windows.html
@@ -0,0 +1 @@
<div></div>
Expand Down

0 comments on commit 7c0a272

Please sign in to comment.