black icon indicating copy to clipboard operation
black copied to clipboard

Check passes on unformatted file after running with line ranges

Open jiteshgulati opened this issue 1 month ago • 0 comments

Describe the bug

When black runs with --line-ranges it still writes the file into the cache as if the whole file was formatted and the next normal run trusts that cache entry and skips the file

So black --check exits 0 on a file that still needs formatting and a plain black run doesnt format the rest of the file either

It also happens with black --check --line-ranges which never writes to the file at all

Looks like the cause is the cache write at the end of reformat_one in src/black/__init__.py which doesnt check lines and the cache key doesnt include the line ranges

To Reproduce

Take this file

x  =  1
y  =  2

And run

$ black --line-ranges 1-1 file.py
$ black -v --check file.py

The second command says

file.py wasn't modified on disk since last run. 1 file would be left unchanged.

and exits 0 but line 2 is still y = 2

With --no-cache the same check says would reformat file.py and exits 1

Same thing with a ranged check on a file where only line 1 is formatted

$ black --check --line-ranges 1-1 file.py
$ black file.py

The second run prints 1 file left unchanged. and line 2 never gets formatted

Expected behavior

A --line-ranges run shouldnt mark the file as formatted in the cache

A later full black --check should exit 1 and a full black run should format the whole file just like with --no-cache

Environment

  • Black's version: 26.5.1 and main (994ef7e)
  • OS and Python version: Linux (WSL2) with Python 3.12 and Windows 11 with Python 3.13

Additional context

This only shows up when the ranged run and the full run share the same cache like local dev or pre-commit or a CI job that keeps the black cache around

Editors that pipe code through stdin dont touch the cache so they arent affected

I have a fix ready that skips the cache write when line ranges are used plus a regression test and Im happy to open a PR

jiteshgulati avatar Oct 03 '26 07:10 jiteshgulati