Skip to content

Using Pre-commit

Pre-commit is a system that lets you run hooks (programs or scripts) after you issue a git commit command, before the commit is executed.

Pre-requisites

The pre-commit executable

Installation options:

  • pip install pre-commit
  • Use Nix
  • Additional can be found here

Basics

  1. Add a .pre-commit-config.yaml file to your project and the following boilerplate configuration.
yaml
# 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: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
      - id: detect-private-key
      - id: no-commit-to-branch
        args: [--branch, staging, --branch, master, --branch, main]
# 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: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
      - id: detect-private-key
      - id: no-commit-to-branch
        args: [--branch, staging, --branch, master, --branch, main]
  1. Run pre-commit install. This will install the hooks specified in the configuration.

Ta da! You have pre-commit up and running. When you make a commit you should now see output outlining the pre-commit checks that were conducted.

sh
$ git add -A
$ git commit -m "test: add file IO failure case"
trim trailing whitespace.................................................Passed
fix end of files.........................................................Passed
...
$ git add -A
$ git commit -m "test: add file IO failure case"
trim trailing whitespace.................................................Passed
fix end of files.........................................................Passed
...

For additional hooks refer to the pre-commit website.

Using with CI/CD

Run pre-commit on all files

sh
pre-commit run --all-files
pre-commit run --all-files

Add to GitLab pipeline

yaml
enforce-pre-commit:
    stage: build
    image: alpine
    only:
        - branches
    before_script: []
    script:
		- apk add pre-commit
        - pre-commit run --all-files
enforce-pre-commit:
    stage: build
    image: alpine
    only:
        - branches
    before_script: []
    script:
		- apk add pre-commit
        - pre-commit run --all-files