21

I just got Black and Pre-Commit set up for my Django repository.

I used the default config for Black from the tutorial I followed and it's been working great, but I am having trouble excluding my migrations files from it.

Here is the default configuration I've been using:

pyproject.toml

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
)/
'''

I used Regex101.com to make sure that ^.*\b(migrations)\b.*$ matched apps/examples/migrations/test.py.

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
  | ^.*\b(migrations)\b.*$
)/
'''

When I add that regex line to my config file, and run pre-commit run --all-files, it ignores the .git folder but still formats the migrations files.

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
Clark Sandholtz
  • 701
  • 6
  • 14

5 Answers5

19

Add the migration exclusion to your .pre-commit-config.yaml file

- id: black
  exclude: ^.*\b(migrations)\b.*$
anthony sottile
  • 61,815
  • 15
  • 148
  • 207
Antony Orenge
  • 439
  • 5
  • 8
  • There is a reason to configure your tools in pyproject.toml (and others) instead of `pre-commit`'s config: you wan't to configure them in one place and have it working in your IDE/CLI/whatever and not just in `pre-commit`. – smido Apr 11 '23 at 10:00
9

That's the solution to the problem: pyproject.toml

[tool.black]
exclude = '''
/(
  | migrations
)/

'''
  • Can you pass the documentation on where you take this syntax under the exclude option? Is this part of TOML language or black? Couldn't find it in Black docs... – tikej Jun 07 '21 at 18:07
  • Sorry, I don't remember where I got this, it was already in my project :( – Elinaldo Monteiro Jun 08 '21 at 12:54
2

Try this (note last line):

[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
  | migrations
)/
'''
tee
  • 4,149
  • 1
  • 32
  • 44
2

Maintaining two different places for exclude config doesn't look good if avoidable and will not work well for the CI either (should you want to dry run black in the PR checks). Adding the following works for the pyproject.toml and then you can run the same in the pre-commit hook and CI:

[tool.black]
...
exclude = '''

(
  /(
    ...
    | .+/migrations
  )/
)
'''
maylon
  • 311
  • 2
  • 4
1

to just extend the default exlusions (without adding the whole list), you can just do:

[tool.black]
extend-exclude = '''
/(
  | migrations
)/
'''
fvmac
  • 11
  • 2