Skip to content

Fix backslash carriage return comments #4663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- Fix crash when a tuple appears in the `as` clause of a `with` statement
(#4634)
- Fix crash when tuple is used as a context manager inside a `with` statement (#4646)
- Fix crash when formatting a `\` followed by a `\r` followed by a comment (#4663)

### Preview style

Expand Down
2 changes: 1 addition & 1 deletion src/black/comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> list[ProtoComment]:
nlines = 0
ignored_lines = 0
form_feed = False
for index, full_line in enumerate(re.split("\r?\n", prefix)):
for index, full_line in enumerate(re.split("\r?\n|\r", prefix)):
consumed += len(full_line) + 1 # adding the length of the split '\n'
match = re.match(r"^(\s*)(\S.*|)$", full_line)
assert match
Expand Down
14 changes: 14 additions & 0 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -2064,6 +2064,20 @@ def test_lines_with_leading_tabs_expanded(self) -> None:
assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"]
assert lines_with_leading_tabs_expanded("\tx\n y") == [f"{tab}x", " y"]

def test_carriage_return_edge_cases(self) -> None:
# These tests are here instead of in the normal cases because
# of git's newline normalization and because it's hard to
# get `\r` vs `\r\n` vs `\n` to display properly
assert (
black.format_str(
"try:\\\r# type: ignore\n pass\nfinally:\n pass\n",
mode=black.FileMode(),
)
== "try: # type: ignore\n pass\nfinally:\n pass\n"
)
assert black.format_str("{\r}", mode=black.FileMode()) == "{}\n"
assert black.format_str("pass #\r#\n", mode=black.FileMode()) == "pass #\n#\n"


class TestCaching:
def test_get_cache_dir(
Expand Down
Loading