Shivam Bhatnagar
It’s certain that as you go about developing code in your regular workflow you will end up pushing mistakes into your git commits. The result of a mistake can be either a small slip-up or a more major issue which causes issues with the application that you are working on.
Pre-commit is a simple to use tool with which you can manage hooks in your project that will run with every commit that you make
References
Why pre-commit
Git has a built-in concept of hooks that allow you to define and run hooks by creating a folder named hooks
inside the .git
directory.
The .git
directory must NOT be checked into your source control, so the down-side of this approach is that you are required to manually copy hooks to another project / developer if need be
pre-commit
is a package manager for hooks. It allows you to specify, using a config file, the hooks you need and it will make sure that these are installed and executed before any commit
How to install pre-commit
Make sure you are working in a git directory, if you don’t then you can initialise one using git init
- Install pre-commit :
pip install pre-commit
- Create pre-commit config : Create a file that is named
pre-commit-config.yaml
- Install the pre-commit hooks :
pre-commit install
Suggested pre-commit config
For a python project
repos:
- repo: 'https://github.com/pre-commit/pre-commit-hooks'
rev: v4.4.0
hooks:
- id: end-of-file-fixer
- id: check-added-large-files
- id: check-toml
- id: check-ast
- id: check-json
exclude: .devcontainer/devcontainer.json
- id: check-case-conflict
- id: double-quote-string-fixer
- id: check-executables-have-shebangs
- id: check-merge-conflict
- id: trailing-whitespace
- repo: 'https://github.com/adrienverge/yamllint'
rev: v1.32.0
hooks:
- id: yamllint
args:
- '--config-file'
- .yamllint.yaml
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.3.4'
hooks:
- id: ruff
- id: ruff-format
Running pre-commit
Local Assuming pre-commit is installed in your repo, then it will run whenever you make a commit. Crucially hooks will only run against files that have been changed and added to a given commit
CI/CD It is recommended to have a CI/CD job which runs pre-commit on all files in the project. This can be achieved by running the following command from within a job
pre-commit run --all-files --show-diff-on-failure
This will ensure that all files follow the hooks defined in the pre-commit-config.yaml