Skip to content

Commit

Permalink
Use two hooks for black: to check, and format
Browse files Browse the repository at this point in the history
This splits the pre-commit hook for black into two hooks, both
using the same repo and id but separately aliased:

- black-check, which checks but does not modify files. This only
  runs when the manual stage is specified, and it is used by tox
  and on CI, with tox.ini and lint.yml modified accordingly.

- black-format, which autoformats code. This provides the behavior
  most users will expect from a pre-commit hook for black. It runs
  automatically along with other hooks. But tox.ini and lint.yml,
  in addition to enabling the black-check hook, also explicitly
  skip the black-format hook.

The effect is that in ordinary development the pre-commit hook for
black does auto-formatting, but that pre-commit continues to be
used effectively for running checks in which code should not be
changed.
  • Loading branch information
EliahKagan committed Oct 3, 2023
1 parent 4ba5ad1 commit 5d8ddd9
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 7 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ jobs:
python-version: "3.x"

- uses: pre-commit/action@v3.0.0
with:
extra_args: --hook-stage manual
env:
SKIP: black-format
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@ repos:
rev: 23.9.1
hooks:
- id: black
alias: black-check
name: black (check)
args: [--check, --diff]
exclude: ^git/ext/
stages: [manual]

- id: black
alias: black-format
name: black (format)
exclude: ^git/ext/

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,22 +142,22 @@ To test, run:
pytest
```

To lint, run:
To lint, and apply automatic code formatting, run:

```bash
pre-commit run --all-files
```

To typecheck, run:
Code formatting can also be done by itself by running:

```bash
mypy -p git
```
black .
```

For automatic code formatting, run:
To typecheck, run:

```bash
black .
mypy -p git
```

Configuration for flake8 is in the `./.flake8` file.
Expand Down
4 changes: 3 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ commands = pytest --color=yes {posargs}
[testenv:lint]
description = Lint via pre-commit
base_python = py39
commands = pre-commit run --all-files
set_env =
SKIP = black-format
commands = pre-commit run --all-files --hook-stage manual

[testenv:mypy]
description = Typecheck with mypy
Expand Down

0 comments on commit 5d8ddd9

Please sign in to comment.