Avoid unstable formatting when comment follows escaped newline. (#839). Fixes #767.

This commit is contained in:
Carl Meyer 2019-05-08 09:53:20 -04:00 committed by GitHub
parent f50ba078b3
commit 6fdbdb4ee3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 35 additions and 1 deletions

View File

@ -2145,15 +2145,21 @@ def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
consumed = 0
nlines = 0
ignored_lines = 0
for index, line in enumerate(prefix.split("\n")):
consumed += len(line) + 1 # adding the length of the split '\n'
line = line.lstrip()
if not line:
nlines += 1
if not line.startswith("#"):
# Escaped newlines outside of a comment are not really newlines at
# all. We treat a single-line comment following an escaped newline
# as a simple trailing comment.
if line.endswith("\\"):
ignored_lines += 1
continue
if index == 0 and not is_endmarker:
if index == ignored_lines and not is_endmarker:
comment_type = token.COMMENT # simple trailing comment
else:
comment_type = STANDALONE_COMMENT

View File

@ -0,0 +1,18 @@
def bob(): \
# pylint: disable=W9016
pass
def bobtwo(): \
\
# some comment here
pass
# output
def bob(): # pylint: disable=W9016
pass
def bobtwo(): # some comment here
pass

View File

@ -75,6 +75,8 @@ def __init__(self):
@fast(really=True)
async def wat():
# This comment, for some reason \
# contains a trailing backslash.
async with X.open_async() as x: # Some more comments
result = await x.method1()
# Comment after ending a block.

View File

@ -396,6 +396,14 @@ def test_comments7(self) -> None:
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_comment_after_escaped_newline(self) -> None:
source, expected = read_data("comment_after_escaped_newline")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data("cantfit")