Force-excluded stdin input is not echoed back unchanged
Describe the bug
When a file passed through stdin matches --force-exclude, Black prints the input back unchanged (added in #4610). It does this with sys.stdout.write(sys.stdin.read()), which reads and writes the content as text, so the output is not always the same as the input:
- On Windows, LF line endings come back as CRLF.
- If the file is not UTF-8 and stdin decodes strictly, Black crashes with
UnicodeDecodeErrorand prints nothing. - With
--checkor--diff, the whole file is printed to stdout.
Editors that format through stdin with --stdin-filename replace the buffer with this output, so a file that should be left alone gets changed.
To Reproduce
With this pyproject.toml:
[tool.black]
force-exclude = "gen/"
and gen/lf.py containing x = 1 with an LF line ending, run this on Windows:
$ black -q --stdin-filename gen/lf.py - < gen/lf.py
The output is x = 1\r\n instead of x = 1\n.
With --check, the file is printed even though nothing should be written:
$ black -q --check --stdin-filename gen/lf.py - < gen/lf.py
x = 1
With a latin-1 file and strict UTF-8 stdin:
$ printf '# -*- coding: latin-1 -*-\ns = "\xe9"\n' > gen/latin.py
$ PYTHONIOENCODING=utf-8:strict black -q --stdin-filename gen/latin.py - < gen/latin.py
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 31: invalid continuation byte
Expected behavior
The output should be exactly the bytes that were passed in. With --check or --diff, nothing should be printed, the same as for a file that needs no changes.
Environment
- Black's version: main (11cff13)
- OS and Python version: Windows with Python 3.13.5, Linux with Python 3.14.7
Additional context
The code is in main() in src/black/__init__.py. I have a fix with a test and will open a PR.