How To Set Up git pre-commit
Git pre-commit hooks are scripts that run automatically before a commit is created. They are a powerful way to enforce project standards, run tests, or perform checks on your code. By using pre-commit hooks, you can ensure that your commits adhere to certain criteria, preventing bad code from entering your repository.
pre-commit
is a Python package that acts as a package manager for pre-commit hooks. Using this package makes it easy to have common hooks for a team working out of a repository with minimal configuration.
Installation
Install pre-commit
with pip.
pip install pre-commit
Configuration
In order to set up pre-commit
, a .pre-commit-config.yaml
file should be placed in the root directory of the git repository.
An example configuration:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0 # Use the ref you want to point at
hooks:
- id: check-yaml
- id: trailing-whitespace
- id: end-of-file-fixer
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.95.0 # Get the latest from: https://github.com/antonbabenko/pre-commit-terraform/releases
hooks:
- id: terraform_fmt
This configuration will remove trailing whitespaces from lines, fix the no-line-at-end-of-file error, run black on python files, and run terraform fmt on terraform files.
This configuration file can be placed directly in the repository, or you can symlink to a common one that you keep in a configuration directory.
In order for the hooks to actually be run upon commit, run pre-commit install
in the root of the directory.
Usage
Make changes to files, and commit as you would normally.
In this example, I've added the ruff
pre-commit hooks and it's found some formatting issues with my code. The commit did not actually go through.
If I run git diff here, I'll see the changes that were made. I can verify they're correct, and run git add -u
to add the changes.
Then running the same command in my history, git commit -m "test pre-commit"
will make the commit.
Conclusion
Pre-commit hooks are a convenient tool for keeping a repository conformant with standards. Consider exploring them for your next project, or implement them in an existing one.