Exclude some files on running black using pre-commit

Viewed 29577

I want to configure black in pre-commit and exclude precommit from checking any migrations folder.

My pyproject.toml looks like this

[tool.black]
line-length = 79
target-version = ['py37']
include = '\.pyi?$'
exclude = '''

(
  /(
      \.eggs
    | \.git
    | \.hg
    | \.mypy_cache
    | \.tox
    | \.venv
    | _build
    | buck-out
    | build
    | dist
  )/
  | ^migrations/
'''

I have also configured precommit. But on running pre-commit run --all-files Black formats the migration folders also how can I configure black

2 Answers

this issue on the black issue tracker outlines your particular problem

pre-commit finds all the python files, then applies pre-commit's exclusion, and then passes that list of files to the underlying tools (in this case black)

black currently (at the time of writing) will format all files listed on the command line -- independent of black's exclude pattern

the suggestion is to use pre-commit's exclusion (via your .pre-commit-config.yaml) such that those files are never passed to black at all:

-   id: black
    exclude: ^migrations/

note: unlike black, pre-commit will only ever lint files which are checked into your git repository, so the laundry list of exclusion is unnecessary here (.git / .mypy_cache / etc.)


disclaimer: I'm the author of pre-commit

Currently, you can use black option --force-exclude. As indicated in the documentation:

--force-exclude TEXT Like --exclude, but files and directories matching this regex will be excluded even when they are passed explicitly as arguments.

So, in your pyproject.toml change exclude to force-exclude.

Related