-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Description
Describe the bug
When multiple files are passed to black, it finds a root that may be incorrect with respect to some of the files it needs to format, resulting in a stack trace under certain conditions:
ValueError: '/home/user/project/tests/bar.py' does not start with '/home/user/project/src'
To Reproduce
Create a directory structure as such:
▾ src/
foo.py
pyproject.toml
▾ tests/
bar.py
poetry.lock
pyproject.toml -> /home/user/project/src/pyproject.toml
run
black src/foo.py tests/bar.py
The soft-linked pyproject.toml is not necessary to reproduce the bug, but it will trigger a stack trace most clearly. Otherwise the root will be incorrect, but it won't cause immediate problems.
Expected behavior
Black should run without dumping a stack trace. Running
black .
succeeds without any problems, so the above should probably perform similarly.
Environment (please complete the following information):
- Version: master
- OS and Python version: Fedora 31/Python 3.7.4
Does this bug also happen on master?
yes
Additional context
As far as I can tell the bug is here. I believe the ordering of python Path objects is purely alphabetical, which makes this work incorrectly -- it just gets the alphabetically first file you give it.
A line like this would work better, IMO:
common_base = max(set.intersection(*(set(path.parents) for path in paths)), key=lambda x: x.parts)
I can make a PR to fix this.
For context, the above trace is getting triggered when running black as a pre-commit hook on a repo where both the code and some tests have been edited in the same commit. I have a linked pyproject.toml in my package so that I can easily access package metadata from within the software from single source of truth. This bug is preventing me from making a commit without separating out the tests (breaking CI on the first commit) or disabling pre-commit (sad!)
Thank you all for all the work a great tool!