Skip to content

Automating the boring stuff with Pre-Commit

Pre-commit runs scripts to check for simple issues before changes are committed. It is able to automatically fix small issues such as trailing whitespace and empty lines at the end of a file.

How to install Pre-commit

Pre-commit can be installed by running:

pip install pre-commit

Configuring

Pre-commit uses a configuration file named .pre-commit-config.yaml, which lists the hooks that pre-commit should call when it is run. A basic configuration can be obtained from pre-commit itself by running:

Format

% pre-commit sample-config

Result

# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files

Using what you've learnt earlier, we can redirect this output to a file named .pre-commit-config.yaml. I'll let you try to remember the command, if you can't you can expand the box below.

Redirect output command
% pre-commit sample-config > .pre-commit-config.yaml

For Pre-Commit to run automatically during commits, it has to be installed - this downloads the hooks and installs them under the .git directory. To install the git hook scripts run:

Format

% pre-commit install

Now Pre-commit should automatically run on git commit or cz c!

If Pre-commit is being added to an existing project or if new hooks have been added, you can run Pre-commit against all files using pre-commit run --all-files. Since we just added it to your repository, let's go ahead and run the command:

Format

% pre-commit run --all-files

Caution

Pre-commit will only run on changed files when called from a git hook! Therefore, it is recommended to use pre-commit run --all-files after adding new hooks.

Hooks

Depending on the purpose of the repository, there are additional hooks that you will want to add to the config file. Since we just learnt about Commitizen, let's add that as the first additional hook. Open up the .pre-commit-config.yaml file and append the following:

Commitizen hook config

- hooks:
  - id: commitizen
    stages:
    - commit-msg
repo: https://github.com/commitizen-tools/commitizen
rev: v2.24.0

Other useful hooks for pre-commit

 - repo: https://github.com/psf/black
        rev: 21.12b0
        hooks:
        - id: black
- repo: https://github.com/pycqa/pydocstyle
rev: 6.1.1  # pick a git hash / tag to point to
hooks:
    - id: pydocstyle
    args: [--convention=numpy, --add-ignore=D104]

Note

Various conventions can be chosen: numpy, google, ...

Further information on the hook mappings is found here.

Next step

With Pre-Commit successfully added to your repository, you are ready to continue on to GitHub - Part 2!