Before you can run hooks, you need to have the pre-commit package manager installed.
Using pip:
pip install pre-commit
In a python project, add the following to your requirements.txt (or requirements-dev.txt):
pre-commit
As a 0-dependency zipapp:
- locate and download the
.pyz
file from the github releases - run
python pre-commit-#.#.#.pyz ...
in place ofpre-commit ...
- follow the install instructions above
pre-commit --version
should show you what version you're using
pre-commit --version
- create a file named
.pre-commit-config.yaml
- you can generate a very basic configuration using
pre-commit sample-config
- the full set of options for the configuration are listed below
- this example uses a formatter for python code, however
pre-commit
works for any programming language - other supported hooks are available
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
- run
pre-commit install
to set up the git hook scripts
$ pre-commit install
pre-commit installed at .git/hooks/pre-commit
- now
pre-commit
will run automatically ongit commit
!
- it's usually a good idea to run the hooks against all of the files when adding
new hooks (usually
pre-commit
will only run on the changed files during git hooks)
$ pre-commit run --all-files
[INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Initializing environment for https://github.com/psf/black.
[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/psf/black.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
Check Yaml...............................................................Passed
Fix End of Files.........................................................Passed
Trim Trailing Whitespace.................................................Failed
- hook id: trailing-whitespace
- exit code: 1
Files were modified by this hook. Additional output:
Fixing sample.py
black....................................................................Passed
- oops! looks like I had some trailing whitespace
- consider running that in CI too