Skip to content

Commit

Permalink
Remove whitespaces of whitespace-only files
Browse files Browse the repository at this point in the history
Currently, empty and whitespace-only (with or without newlines) are
not modified. In some discussions (issues and pull requests) consesus
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 <[email protected]>
  • Loading branch information
aaossa committed Oct 21, 2022
1 parent 575220f commit 74861f0
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/black/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -914,9 +914,6 @@ def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileCo
valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
`mode` is passed to :func:`format_str`.
"""
if not src_contents.strip():
raise NothingChanged

if mode.is_ipynb:
dst_contents = format_ipynb_string(src_contents, fast=fast, mode=mode)
else:
Expand Down Expand Up @@ -1011,6 +1008,9 @@ def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> FileCon
Operate cell-by-cell, only on code cells, only for Python notebooks.
If the ``.ipynb`` originally had a trailing newline, it'll be preserved.
"""
if not src_contents:
raise NothingChanged

trailing_newline = src_contents[-1] == "\n"
modified = False
nb = json.loads(src_contents)
Expand Down Expand Up @@ -1100,6 +1100,11 @@ def _format_str_once(src_contents: str, *, mode: Mode) -> str:
current_line, mode=mode, features=split_line_features
):
dst_contents.append(str(line))
if not dst_contents:
normalized_content, _, newline = decode_bytes(src_contents.encode("utf-8"))
if "\n" in normalized_content:
return newline
return ""
return "".join(dst_contents)


Expand Down

0 comments on commit 74861f0

Please sign in to comment.