忽略 pyproject.toml 黑色格式化程序文件中的 Django 迁移

Ignoring Django Migrations in pyproject.toml file for Black formatter

我刚刚 Black and Pre-Commit 设置了我的 Django 存储库。

我使用了我遵循的教程中的 Black 默认配置,它运行良好,但我无法从中排除我的迁移文件。

这是我一直使用的默认配置:

pyproject.toml

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

我使用 Regex101.com 来确保 ^.*\b(migrations)\b.*$ 匹配 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.*$
)/
'''

当我将该正则表达式行添加到我的配置文件和 运行 pre-commit run --all-files 时,它会忽略 .git 文件夹,但仍会格式化迁移文件。

试试这个(注意最后一行):

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

将迁移排除项添加到您的 .pre-commit-config.yaml 文件

- id: black
  exclude: ^.*\b(migrations)\b.*$

这就是问题的解决方案:pyproject.toml

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

'''

如果可以避免,为 exclude 配置保留两个不同的位置看起来不太好,对 CI 也不会很好(如果你想在 运行 中擦干黑色公关检查)。 为 pyproject.toml 添加以下工作,然后您可以 运行 在预提交挂钩和 CI 中使用相同的方法:

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

(
  /(
    ...
    | .+/migrations
  )/
)
'''