empty lines at end of file trimmed even with fmt: off
Operating system: Linux Mint Python version: 3.6.6 Black version: latest Does also happen on master: yes
The following file:
# fmt: off
print("hello")
gets trimmed to:
# fmt: off
print("hello")
IOW, if the file ends with empty lines, they are removed.
Sounds like a bug. Want to take a look at fixing it?
The problem here appears to happen in convert_one_fmt_off_pair, where the node enters as # fmt: off\n\nprint("hello")\n\n and exits as # fmt: off\n\nprint("hello")\n. I am continuing to investigate.
The function generate_ignored_nodes creates a list of nodes that is just # fmt: off\n\nprint("hello")\n. This is where the final newline is lost.
Unfortunately, I've reached the end of my experience/time to look at this today. I hope this has given someone more versed in the project a better starting place for fixing this bug.
EDIT: also, because of how test files are read in read_data in test_black.py, it will be difficult to write a test for this since the final \n will be removed.
At least our documentation states that fmt: off should be followed by a fmt: on, but supporting a single off switch is a reasonable request.
I reproduced this on the current development branch (26.5.2.dev98+g8947c48ef, CPython 3.12.3).
Minimal input:
# fmt: off
print("hello")
Running black file.py removes the final blank line and produces:
# fmt: off
print("hello")
The issue is that the parser stores trailing blank lines after the final statement in the END marker prefix, while fmt-off conversion currently discards that prefix. I have a focused fix that preserves the END marker prefix for an unclosed # fmt: off block at EOF, together with a regression test through Black’s file-formatting path.