Introduction
Pre-commit is a framework for managing and enforcing Git pre-commit hooks. It helps automating code quality checks before committing changes, ensuring that issues like formatting, linting, and security vulnerabilities are caught early.
Essentially, pre-commit runs a range of checks automatically before each Git commit. Not only does it highlight issues, but it can also fix them before they even make it into your repository.
Why Should You Use Pre-Commit?
How often do you review pull requests and find unformatted code? Or worse - exposed secrets, passwords, or API keys?
When sensitive information leaks into a repository, it requires secret rotation, repo cleanups, and security reviews — all of which take time and effort.
With pre-commit, you can prevent these issues before they ever reach Git, saving time and improving code quality.
Why Is Pre-Commit Amazing?
- Automates Code Quality Checks – No more manual linting or formatting.
- Prevents Common Mistakes – Catches syntax errors and validates code.
- Detects Secrets in Code – Prevents accidental commits of sensitive information.
- Runs Locally and in CI/CD – Works seamlessly on local machine and in pipelines.
- Works with Any Language – Supports Python, JavaScript, Terraform, and many more.
- Fast and Efficient – Runs only on staged files for quick checks.
- Supports External Hooks – Use hooks from external repositories.
- Easy to Set Up – Takes just a few minutes to integrate into any project.
There are also many great repositories with pre-commit hooks available:
And many more! If you haven’t found the functionality you need, you can always create your own hook: 👉 Guide to Creating New Hooks
How to Use Pre-Commit
1. Install Pre-Commit
Using pip:
pip install pre-commit
Using Homebrew (macOS/Linux):
brew install pre-commit
2. Create a Pre-Commit Config File
Inside your repository, create a file named .pre-commit-config.yaml
:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace # Removes trailing spaces
- id: end-of-file-fixer # Ensures newline at EOF
- id: check-yaml # Validates YAML files
This config tells pre-commit to install hooks from the pre-commit-hooks repository and run basic checks.
3. Install hooks
Run this inside your repo:
pre-commit install
This installs Git hooks so they run automatically before every git commit
.
To manually trigger them on all files, run:
pre-commit run -a
Conclusion
Pre-commit is an awesome tool for enforcing code quality, security, and consistency. It automates tedious checks, prevents mistakes, and ensures clean commits before they even reach a repo.
Give pre-commit a try, and make your commits cleaner, safer, and more efficient!