Why I use pre-commit

Posted on Sun 01 January 2023 in Tools

Sometimes when you are working on something and get interrupted, it's easy to forget to fix a small thing before committing and pushing. Pre-commit enables you to have automatic checks before you commit the code. It can be frustrating when the CI fails because of a missing new line or another formatting error.

Pre-commit isn't a replacement for the CI pipelines, so it shouldn't run long-running tasks, for example tests. Anthony Sottile, a pre-commit and pytest maintainer, argues in an issue to add pytest why pytest hasn't have its own hook:

The main reasons:

  1. Tests are often slow, committing should be fast
  2. It would have to be a system / script hook since you'd need repository specific dependencies installed (as you've noticed)

To set it up look at pre-commit homepages.

This is my .pre-commit-config.yaml that I use for Python:

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
  rev: v4.4.0
  hooks:
  - id: check-toml
  - id: check-yaml
  - id: end-of-file-fixer
  - id: no-commit-to-branch
  - id: trailing-whitespace
- repo: https://github.com/psf/black
  rev: 23.7.0
  hooks:
  - id: black
    language_version: python3.10
- repo: https://github.com/astral-sh/ruff-pre-commit
  # Ruff version.
  rev: v0.0.280
  hooks:
    - id: ruff
- repo: https://github.com/pryorda/dockerfilelint-precommit-hooks
  rev: v0.1.0
  hooks:
  - id: dockerfilelint
    stages: [commit]
- repo: https://github.com/igorshubovych/markdownlint-cli
  rev: v0.35.0
  hooks:
  - id: markdownlint