Skip to content

Commit d97b789

Browse files
authored
Remove whitespaces of whitespace-only files (#3348)
Currently, empty and whitespace-only (with or without newlines) are not modified. In some discussions (issues and pull requests) consensus was to reformat whitespace-only files to empty or single-character files, preserving line endings when possible. With that said, this commit introduces the following behaviors: * Empty files are left as is * Whitespace-only files (no newline) reformat into empty files * Whitespace-only files (1 or more newlines) reformat into a single newline character To implement these changes, we moved the initial check at `format_file_contents` that raises `NothingChanged` if the source (with no whitespaces) is an empty string. In the case of *.ipynb files, `format_ipynb_string` checks a similar condition and removed whitespaces. In the case of Python files, `format_str_once` includes a check on the output that returns the correct newline character if possible or an empty string otherwise. Signed-off-by: Antonio Ossa Guerra <aaossa@uc.cl>
1 parent c23a5c1 commit d97b789

File tree

4 files changed

+104
-3
lines changed

4 files changed

+104
-3
lines changed

CHANGES.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
<!-- Changes that affect Black's preview style -->
1616

1717
- Enforce empty lines before classes and functions with sticky leading comments (#3302)
18+
- Reformat empty and whitespace-only files as either an empty file (if no newline is
19+
present) or as a single newline character (if a newline is present) (#3348)
1820
- Implicitly concatenated strings used as function args are now wrapped inside
1921
parentheses (#3307)
2022
- Correctly handle trailing commas that are inside a line's leading non-nested parens

src/black/__init__.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -917,7 +917,7 @@ def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileCo
917917
valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
918918
`mode` is passed to :func:`format_str`.
919919
"""
920-
if not src_contents.strip():
920+
if not mode.preview and not src_contents.strip():
921921
raise NothingChanged
922922

923923
if mode.is_ipynb:
@@ -1014,6 +1014,9 @@ def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> FileCon
10141014
Operate cell-by-cell, only on code cells, only for Python notebooks.
10151015
If the ``.ipynb`` originally had a trailing newline, it'll be preserved.
10161016
"""
1017+
if mode.preview and not src_contents:
1018+
raise NothingChanged
1019+
10171020
trailing_newline = src_contents[-1] == "\n"
10181021
modified = False
10191022
nb = json.loads(src_contents)
@@ -1106,6 +1109,13 @@ def _format_str_once(src_contents: str, *, mode: Mode) -> str:
11061109
dst_contents = []
11071110
for block in dst_blocks:
11081111
dst_contents.extend(block.all_lines())
1112+
if mode.preview and not dst_contents:
1113+
# Use decode_bytes to retrieve the correct source newline (CRLF or LF),
1114+
# and check if normalized_content has more than one line
1115+
normalized_content, _, newline = decode_bytes(src_contents.encode("utf-8"))
1116+
if "\n" in normalized_content:
1117+
return newline
1118+
return ""
11091119
return "".join(dst_contents)
11101120

11111121

tests/data/preview/whitespace.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
3+
4+
5+
6+
# output

tests/test_black.py

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
List,
2626
Optional,
2727
Sequence,
28+
Type,
2829
TypeVar,
2930
Union,
3031
)
@@ -153,6 +154,34 @@ def test_empty_ff(self) -> None:
153154
os.unlink(tmp_file)
154155
self.assertFormatEqual(expected, actual)
155156

157+
@patch("black.dump_to_file", dump_to_stderr)
158+
def test_one_empty_line(self) -> None:
159+
mode = black.Mode(preview=True)
160+
for nl in ["\n", "\r\n"]:
161+
source = expected = nl
162+
assert_format(source, expected, mode=mode)
163+
164+
def test_one_empty_line_ff(self) -> None:
165+
mode = black.Mode(preview=True)
166+
for nl in ["\n", "\r\n"]:
167+
expected = nl
168+
tmp_file = Path(black.dump_to_file(nl))
169+
if system() == "Windows":
170+
# Writing files in text mode automatically uses the system newline,
171+
# but in this case we don't want this for testing reasons. See:
172+
# https://github.com/psf/black/pull/3348
173+
with open(tmp_file, "wb") as f:
174+
f.write(nl.encode("utf-8"))
175+
try:
176+
self.assertFalse(
177+
ff(tmp_file, mode=mode, write_back=black.WriteBack.YES)
178+
)
179+
with open(tmp_file, "rb") as f:
180+
actual = f.read().decode("utf8")
181+
finally:
182+
os.unlink(tmp_file)
183+
self.assertFormatEqual(expected, actual)
184+
156185
def test_experimental_string_processing_warns(self) -> None:
157186
self.assertWarns(
158187
black.mode.Deprecated, black.Mode, experimental_string_processing=True
@@ -971,8 +1000,8 @@ def err(msg: str, **kwargs: Any) -> None:
9711000
)
9721001

9731002
def test_format_file_contents(self) -> None:
974-
empty = ""
9751003
mode = DEFAULT_MODE
1004+
empty = ""
9761005
with self.assertRaises(black.NothingChanged):
9771006
black.format_file_contents(empty, mode=mode, fast=False)
9781007
just_nl = "\n"
@@ -990,6 +1019,17 @@ def test_format_file_contents(self) -> None:
9901019
black.format_file_contents(invalid, mode=mode, fast=False)
9911020
self.assertEqual(str(e.exception), "Cannot parse: 1:7: return if you can")
9921021

1022+
mode = black.Mode(preview=True)
1023+
just_crlf = "\r\n"
1024+
with self.assertRaises(black.NothingChanged):
1025+
black.format_file_contents(just_crlf, mode=mode, fast=False)
1026+
just_whitespace_nl = "\n\t\n \n\t \n \t\n\n"
1027+
actual = black.format_file_contents(just_whitespace_nl, mode=mode, fast=False)
1028+
self.assertEqual("\n", actual)
1029+
just_whitespace_crlf = "\r\n\t\r\n \r\n\t \r\n \t\r\n\r\n"
1030+
actual = black.format_file_contents(just_whitespace_crlf, mode=mode, fast=False)
1031+
self.assertEqual("\r\n", actual)
1032+
9931033
def test_endmarker(self) -> None:
9941034
n = black.lib2to3_parse("\n")
9951035
self.assertEqual(n.type, black.syms.file_input)
@@ -1281,8 +1321,51 @@ def test_reformat_one_with_stdin_and_existing_path(self) -> None:
12811321
report.done.assert_called_with(expected, black.Changed.YES)
12821322

12831323
def test_reformat_one_with_stdin_empty(self) -> None:
1324+
cases = [
1325+
("", ""),
1326+
("\n", "\n"),
1327+
("\r\n", "\r\n"),
1328+
(" \t", ""),
1329+
(" \t\n\t ", "\n"),
1330+
(" \t\r\n\t ", "\r\n"),
1331+
]
1332+
1333+
def _new_wrapper(
1334+
output: io.StringIO, io_TextIOWrapper: Type[io.TextIOWrapper]
1335+
) -> Callable[[Any, Any], io.TextIOWrapper]:
1336+
def get_output(*args: Any, **kwargs: Any) -> io.TextIOWrapper:
1337+
if args == (sys.stdout.buffer,):
1338+
# It's `format_stdin_to_stdout()` calling `io.TextIOWrapper()`,
1339+
# return our mock object.
1340+
return output
1341+
# It's something else (i.e. `decode_bytes()`) calling
1342+
# `io.TextIOWrapper()`, pass through to the original implementation.
1343+
# See discussion in https://github.com/psf/black/pull/2489
1344+
return io_TextIOWrapper(*args, **kwargs)
1345+
1346+
return get_output
1347+
1348+
mode = black.Mode(preview=True)
1349+
for content, expected in cases:
1350+
output = io.StringIO()
1351+
io_TextIOWrapper = io.TextIOWrapper
1352+
1353+
with patch("io.TextIOWrapper", _new_wrapper(output, io_TextIOWrapper)):
1354+
try:
1355+
black.format_stdin_to_stdout(
1356+
fast=True,
1357+
content=content,
1358+
write_back=black.WriteBack.YES,
1359+
mode=mode,
1360+
)
1361+
except io.UnsupportedOperation:
1362+
pass # StringIO does not support detach
1363+
assert output.getvalue() == expected
1364+
1365+
# An empty string is the only test case for `preview=False`
12841366
output = io.StringIO()
1285-
with patch("io.TextIOWrapper", lambda *args, **kwargs: output):
1367+
io_TextIOWrapper = io.TextIOWrapper
1368+
with patch("io.TextIOWrapper", _new_wrapper(output, io_TextIOWrapper)):
12861369
try:
12871370
black.format_stdin_to_stdout(
12881371
fast=True,

0 commit comments

Comments
 (0)