black icon indicating copy to clipboard operation
black copied to clipboard

force-exclude doesnt apply when the file path has .. in it

Open jiteshgulati opened this issue 2 months ago • 0 comments

Describe the bug

If the file path you pass has .. in it black doesnt match it against --force-exclude so an excluded file still gets formatted. The same file passed as generated/gen.py or as an absolute path is skipped like it should be

Looks like best_effort_relative_path in src/black/files.py uses path.absolute() which keeps the .. so the regex is checked against /src/../generated/gen.py instead of /generated/gen.py

To Reproduce

pyproject.toml in the project root

[tool.black]
force-exclude = "^/generated/"

and generated/gen.py

x  =  1

Run it from the src folder

$ cd src
$ black ../generated/gen.py
reformatted ../generated/gen.py
1 file reformatted.

The excluded file is rewritten to x = 1

stdin has the same problem

$ echo 'x  =  1' | black -q --stdin-filename ../generated/gen.py -
x = 1

From the project root black generated/gen.py correctly says there is nothing to do

Expected behavior

The file should be skipped the same way it is when the path has no .. in it

Environment

  • Black's version: 26.5.1 (compiled) and main (994ef7e)
  • OS and Python version: Linux (WSL2) / Python 3.12.14

Additional context

I ran into this with scripts that call black on files from a subdirectory. Collapsing the .. before the regex check fixes it and it can be done without resolving symlinks so the current symlink behaviour stays the same. I have a fix with a test ready and can open a PR

jiteshgulati avatar Oct 02 '26 11:10 jiteshgulati