Skip to content

Commit 017aafe

Browse files
author
simaki
authored
Accept empty stdin (close #2337) (#2346)
Commit history before merge: * Accept empty stdin (close #2337) * Update tests/test_black.py * Add changelog * Assert Black reformats an empty string to an empty string (#2337) (#2346) * fix
1 parent be16cfa commit 017aafe

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
- Add primer support and test for code piped into black via STDIN (#2315)
88
- Fix internal error when `FORCE_OPTIONAL_PARENTHESES` feature is enabled (#2332)
9+
- Accept empty stdin (#2346)
910

1011
## 21.6b0
1112

src/black/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -803,7 +803,8 @@ def format_stdin_to_stdout(
803803
)
804804
if write_back == WriteBack.YES:
805805
# Make sure there's a newline after the content
806-
dst += "" if dst[-1] == "\n" else "\n"
806+
if dst and dst[-1] != "\n":
807+
dst += "\n"
807808
f.write(dst)
808809
elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
809810
now = datetime.utcnow()

tests/test_black.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from contextlib import contextmanager
77
from dataclasses import replace
88
import inspect
9+
import io
910
from io import BytesIO
1011
import os
1112
from pathlib import Path
@@ -1682,6 +1683,20 @@ def test_reformat_one_with_stdin_and_existing_path(self) -> None:
16821683
# __BLACK_STDIN_FILENAME__ should have been stripped
16831684
report.done.assert_called_with(expected, black.Changed.YES)
16841685

1686+
def test_reformat_one_with_stdin_empty(self) -> None:
1687+
output = io.StringIO()
1688+
with patch("io.TextIOWrapper", lambda *args, **kwargs: output):
1689+
try:
1690+
black.format_stdin_to_stdout(
1691+
fast=True,
1692+
content="",
1693+
write_back=black.WriteBack.YES,
1694+
mode=DEFAULT_MODE,
1695+
)
1696+
except io.UnsupportedOperation:
1697+
pass # StringIO does not support detach
1698+
assert output.getvalue() == ""
1699+
16851700
def test_gitignore_exclude(self) -> None:
16861701
path = THIS_DIR / "data" / "include_exclude_tests"
16871702
include = re.compile(r"\.pyi?$")

0 commit comments

Comments
 (0)