From 6fdbdb4ee301d8f9466da4da8364ac05611a1b19 Mon Sep 17 00:00:00 2001 From: Carl Meyer Date: Wed, 8 May 2019 09:53:20 -0400 Subject: [PATCH] Avoid unstable formatting when comment follows escaped newline. (#839). Fixes #767. --- black.py | 8 +++++++- tests/data/comment_after_escaped_newline.py | 18 ++++++++++++++++++ tests/data/comments.py | 2 ++ tests/test_black.py | 8 ++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/data/comment_after_escaped_newline.py diff --git a/black.py b/black.py index 18d60c0..1978fd5 100644 --- a/black.py +++ b/black.py @@ -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 diff --git a/tests/data/comment_after_escaped_newline.py b/tests/data/comment_after_escaped_newline.py new file mode 100644 index 0000000..133f489 --- /dev/null +++ b/tests/data/comment_after_escaped_newline.py @@ -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 diff --git a/tests/data/comments.py b/tests/data/comments.py index 4ae3d2c..a20e653 100644 --- a/tests/data/comments.py +++ b/tests/data/comments.py @@ -75,6 +75,8 @@ class Foo: @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. diff --git a/tests/test_black.py b/tests/test_black.py index 896ad0c..53d1750 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -396,6 +396,14 @@ class BlackTestCase(unittest.TestCase): 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") -- 2.39.5