From 7fc6ce990669464f5172b63fafa3724f5f308be3 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=C5=81ukasz=20Langa?= Date: Mon, 4 Jun 2018 19:04:29 -0700 Subject: [PATCH] Fix handling of empty files --- black.py | 5 ++++- tests/test_black.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/black.py b/black.py index 46c0907..c6b018f 100644 --- a/black.py +++ b/black.py @@ -607,6 +607,9 @@ def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: """ srcbuf = io.BytesIO(src) encoding, lines = tokenize.detect_encoding(srcbuf.readline) + if not lines: + return "", encoding, "\n" + newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n" srcbuf.seek(0) with io.TextIOWrapper(srcbuf, encoding) as tiow: @@ -623,7 +626,7 @@ GRAMMARS = [ def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement - if src_txt[-1] != "\n": + if src_txt[-1:] != "\n": src_txt += "\n" for grammar in GRAMMARS: drv = driver.Driver(grammar, pytree.convert) diff --git a/tests/test_black.py b/tests/test_black.py index f6952c7..e98f019 100644 --- a/tests/test_black.py +++ b/tests/test_black.py @@ -100,6 +100,25 @@ class BlackTestCase(unittest.TestCase): black.err(str(ve)) self.assertEqual(expected, actual) + @patch("black.dump_to_file", dump_to_stderr) + def test_empty(self) -> None: + source = expected = "" + actual = fs(source) + self.assertFormatEqual(expected, actual) + black.assert_equivalent(source, actual) + black.assert_stable(source, actual, line_length=ll) + + def test_empty_ff(self) -> None: + expected = "" + tmp_file = Path(black.dump_to_file()) + try: + self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES)) + with open(tmp_file, encoding="utf8") as f: + actual = f.read() + finally: + os.unlink(tmp_file) + self.assertFormatEqual(expected, actual) + @patch("black.dump_to_file", dump_to_stderr) def test_self(self) -> None: source, expected = read_data("test_black") -- 2.39.2