Stop Committing Broken Code: A 2-Minute Guide to Pre-Commit
2 min read

How to use this guide:
- The Follow-Along: Open your terminal and a sample repo to build this setup in real-time.
- The Cheat Sheet: Bookmark this page and jump straight to the code snippets when you're ready to implement this in your professional projects.
Prerequisites
Before we dive in, ensure you have:
- A Git repository initialized (
git init). - Python, Homebrew, or Chocolatey installed.
- A basic understanding of YAML syntax.
1. Installation
Install the framework globally or within your virtual environment:
- macOS:
brew install pre-commit - Linux:
pip install pre-commit - Windows:
choco install pre-commit
Verify the installation: pre-commit --version
2. Configuration
Create a file named .pre-commit-config.yaml in your root directory. This file tells Git which "tests" to run before allowing a commit.
Pro Tip: Running
pre-commit sample-configis the fastest way to see what the syntax looks like.
3. Choose Your Hooks
You can browse community-maintained hooks here.
Alternatively, you can generate a starter config:
pre-commit sample-configI've also built an example .pre-commit-config.yaml . You can copy this - I've included Gitleaks to ensure you never accidentally push API keys or passwords to GitHub.
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
# Secrets detection hook
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.1
hooks:
- id: gitleaks4. Wire it to Git
Just because the file exists doesn't mean it's running yet. You must "install" the hook script into your .git directory:
pre-commit installOutput: pre-commit installed at .git/hooks/pre-commit
5. The Test Run
To see it in action, stage a file with an error (e.g., leave trailing spaces or a fake API key like api_key = "AKIAIOSFODNN7EXAMPLE") and try to commit:
git add .
git commit -m "Testing security hooks"What happens next:
- Pre-commit intercepts the command.
- It runs the hooks.
- The commit will fail. You'll notice the commit message was never saved to the git log (the "main tree"). You are forced to fix the errors before Git will let the code through.
6. Manual Project Scan
If you've just added pre-commit to an existing project, your old files might still have "hidden" errors. Run a full scan manually:
pre-commit run --all-filesSummary
By following these steps, you’ve essentially built a local CI pipeline. You are no longer relying on a remote server to tell you your YAML is malformed or that you've leaked a secret - you're catching it at the source.