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-config is 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:

shell
pre-commit sample-config

I'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.

yml
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: gitleaks

4. 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:

shell
pre-commit install

Output: 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:

shell
git add .
git commit -m "Testing security hooks"

What happens next:

  1. Pre-commit intercepts the command.
  2. It runs the hooks.
  3. 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:

shell
pre-commit run --all-files

Summary

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.