In this article, I will explain how to set-up a pre-commit pipeline for a Python / Django project. Please note that, although I use Django as an example here, what is written below is applicable to Python projects in general (with some minor adjustments).

What and Why Pre-Commit?

Git supports running hooks at different stages of its workflow(s). For a detailed discussion see the official SCM book. One of these hooks is the “pre-commit” hook, which allows a user to validate and transform code before the commit process.

Pre-Commit, in turn, is a Python package that makes installing and running Git hooks quite straightforward and is a great solution for Python-based or multi-lingual repositories.

Setting-Up Pre-Commit

The simplest way of installing pre-commit in a Python project is by adding it to the project’s requirements.txt (or requirements-dev.txt) file and then installing it into the local virtual environment with:

pip install -r requirements.txt

Or if you use a Pipfile you can add it to the [dev-packages] section and then run:

pipenv install --dev

If this is not optimal for you then check out the documentation that gives several different ways of installing it (e.g. using homebrew or curl).

After you have Pre-Commit installed, the next stage is to add a YAML config file to the root of your repository called “.pre-commit-config.yaml” with the following:

default_language_version:
  python: python3.8
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
      - id: trailing-whitespace
      - id: check-executables-have-shebangs
      - id: debug-statements
      - id: check-merge-conflict
      - id: name-tests-test
        args: ['--django']

In the “default_language_version” section you can pre-define the default version for each supported language used in the repo. You should set this to the Python version used in your project, and if you set up hooks for other supported languages then add these as well.

In the “repos” section in turn we tell pre-commit where to locate or download the hooks from. The “-” is the YAML syntax for array, and this section will have multiple entries. For now, though, we are only referring to the official pre-commit-hooks package repo and each “id” entry under the “hooks” key refers to a specific hook from this package, i.e. we are enabling five different hooks:

#git #python #code #django #tools

Tool Your Django Project: Pre-Commit Hooks
14.75 GEEK