From c7495b9aa098ef7a358fc74556359d21c6a4ba11 Mon Sep 17 00:00:00 2001 From: Joe Antonakakis Date: Sun, 4 Aug 2019 02:03:19 -0700 Subject: [PATCH 1/1] Fix unstable format involving backslash + whitespace at beginning of file (#948) --- black.py | 8 +++++++- tests/data/beginning_backslash.py | 12 ++++++++++++ tests/test_black.py | 8 ++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/data/beginning_backslash.py diff --git a/black.py b/black.py index f7022d8..05edf1a 100644 --- a/black.py +++ b/black.py @@ -1480,7 +1480,13 @@ class EmptyLineTracker: lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) - before -= self.previous_after + before = ( + # Black should not insert empty lines at the beginning + # of the file + 0 + if self.previous_line is None + else before - self.previous_after + ) self.previous_after = after self.previous_line = current_line return before, after diff --git a/tests/data/beginning_backslash.py b/tests/data/beginning_backslash.py new file mode 100644 index 0000000..66c347d --- /dev/null +++ b/tests/data/beginning_backslash.py @@ -0,0 +1,12 @@ +\ + + + + + +print("hello, world") + +# output + + +print("hello, world") diff --git a/tests/test_black.py b/tests/test_black.py index 7b3a8b6..015243f 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -639,6 +639,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_beginning_backslash(self) -> None: + source, expected = read_data("beginning_backslash") + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, black.FileMode()) + def test_tab_comment_indentation(self) -> None: contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n" contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n" -- 2.39.5