Unverified Commit 6fdbdb4e authored by Carl Meyer's avatar Carl Meyer Committed by GitHub
Browse files

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

parent f50ba078
Loading
Loading
Loading
Loading
+7 −1
Changes for black.py: 7 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -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
+18 −0
Changes for tests/data/comment_after_escaped_newline.py: 18 added lines, 0 removed lines.
Original line number Diff line number Diff line
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
+2 −0
Changes for tests/data/comments.py: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -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.
+8 −0
Changes for tests/test_black.py: 8 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -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")