tezvyn:

Pre-commit Hooks: Your Code's Quality Gatekeeper

AI-drafted, machine-checkedSource: git-scm.combeginner

Think of a pre-commit hook as a bouncer for your codebase. It's a script that runs before Git finalizes a commit, checking your changes against project rules. Use it to automatically lint code, run formatters, or check for secrets before they enter history.

WHY IT EXISTS: To prevent simple mistakes and enforce coding standards before they are recorded in the project's history. Manually running linters, formatters, and other checks is error-prone. Automating this process at the commit stage catches issues early and maintains code quality.

THE MENTAL MODEL: A pre-commit hook is a script that acts as a quality gate for your git commit command. Before Git saves your changes, it runs this script. If the script finishes successfully (exits with code 0), the commit proceeds. If it fails (exits with a non-zero code), Git aborts the commit, forcing you to fix the issues. It's a personal, local safety net.

HOW IT WORKS: When you run git commit, Git checks for an executable file named pre-commit inside the local .git/hooks/ directory. If found, Git executes it. The script can inspect all the files you've staged for the commit. Common tasks include running linters (like Stylelint for CSS), code formatters (like Prettier), or custom scripts. If any of these checks fail, the script exits with a non-zero status code, and Git prints the script's output to your terminal and cancels the commit.

WHEN TO USE IT: Use pre-commit hooks for fast, automated checks that provide immediate feedback to a developer. This is ideal for linting CSS or JavaScript, formatting code to a consistent style, or running quick unit tests relevant to the changed files. It helps keep the main branch clean from trivial errors and style inconsistencies.

WHEN NOT TO USE IT: Don't use pre-commit hooks for long-running tasks like a full integration test suite, which would make committing painfully slow. Also, because hooks are not automatically shared when a repository is cloned, they cannot be the only enforcement mechanism. Critical checks must also be run in a shared CI/CD pipeline to ensure all code meets quality standards.

ONE CANONICAL EXAMPLE: In a design system project, a hook might run prettier --write on all staged .css and .js files to enforce formatting, followed by stylelint to check for CSS rule violations. If Stylelint finds an error, it will exit non-zero, blocking the commit and showing the developer exactly which CSS rule was broken.

Read the original → git-scm.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.