Skip to content

Commit

Permalink
Preserve crlf newlines in blackd
Browse files Browse the repository at this point in the history
  • Loading branch information
KotlinIsland committed Sep 5, 2022
1 parent 92c93a2 commit 3ce63e1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGES.md
Expand Up @@ -36,7 +36,7 @@

### _Blackd_

<!-- Changes to blackd -->
- Windows style (CRLF) newlines will be preserved (#3257).

### Integrations

Expand Down
7 changes: 7 additions & 0 deletions src/blackd/__init__.py
Expand Up @@ -133,6 +133,13 @@ async def handle(request: web.Request, executor: Executor) -> web.Response:
executor, partial(black.format_file_contents, req_str, fast=fast, mode=mode)
)

# Preserve CRLF newlines
if req_str[req_str.find("\n") - 1] == "\r":
formatted_str = formatted_str.replace("\n", "\r\n")
# If, after swapping newlines, nothing changed, then say so
if formatted_str == req_str:
raise black.NothingChanged

# Only output the diff in the HTTP response
only_diff = bool(request.headers.get(DIFF_HEADER, False))
if only_diff:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_blackd.py
Expand Up @@ -212,3 +212,13 @@ async def test_cors_headers_present(self) -> None:
response = await self.client.post("/", headers={"Origin": "*"})
self.assertIsNotNone(response.headers.get("Access-Control-Allow-Origin"))
self.assertIsNotNone(response.headers.get("Access-Control-Expose-Headers"))

@unittest_run_loop
async def test_preserve_newline(self) -> None:
for data in (b"c\r\nc\r\n", b"l\nl\n"):
# test preserved newlines when reformatted
response = await self.client.post("/", data=data + b" ")
self.assertEqual(await response.text(), data.decode())
# test 204 when no change
response = await self.client.post("/", data=data)
self.assertEqual(response.status, 204)

0 comments on commit 3ce63e1

Please sign in to comment.