pre-commit implementation notes#
In this article, we will explain how to introduce and utilize pre-commit, a tool that automatically formats and checks code and documents before committing to Git.
Introduction: What is pre-commit?#
pre-commit is a Python tool for easily managing and operating Git’s “pre-commit hooks”. You can automate tasks such as:
Line break check at end of file
Formatting Python code (Black)
Markdown and reStructuredText grammar check
YAML/JSON/TOML syntax checking
Detection of security-risky code (e.g. Bandit)
Installation and initial configuration#
First, install pre-commit. It can be used in a virtual environment or the entire system.
pip install pre-commit
Or if you’re a pipx fan:
pipx install pre-commit
Next, create .pre-commit-config.yaml at the root of your project.
Basic example:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 24.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
- id: flake8
Installing the hook:
pre-commit install
This will automatically run the check on your next git commit.
Version control and automatic updates#
All hooks have a version (rev) specified and can be updated in bulk with the following command:
pre-commit autoupdate
Document checking with pre-commit#
Lightweight markup like Markdown and reStructuredText can also be maintained with pre-commit.
doctoc: Markdown table of contents automatic generationmdformat: Automatic formatting of Markdown (made in Python)doc8: reStructuredText rule checkrstcheck: Syntax validation for Sphinx
If you use pre-commit to automatically generate a table of contents and format API documentation, the big advantage is that you can prevent documents from becoming obsolete while also being able to show them as differences.
If you want to check all files, use the following command:
pre-commit run --all-files
Since pre-commit automatically performs format corrections, etc., files may be changed unintentionally. In that case, you can revert to the most recent commit with the following command:
git restore --source=HEAD --staged --worktree .
Thorough pre-commit#
The hook runs on every commit, which has the following effects:
Quality maintenance is guaranteed “automatically”
Unification of Lint/formatting rules is forced
Detect problems locally before CI notices them
If you are working with a team, clearly stating the following in your README or CONTRIBUTING will help make it more established:
pre-commit install
summary#
We have organized the basics of implementation regarding pre-commit. In the future, we would like to consider comprehensive settings and collaboration with CI.
Article information
- Post date:
2025-05-16
- author:
Mr. Takagi