Git Hooks Automation: pre-commit, commit-msg, and pre-push as Three Gates Before Bad Code Leaves Your Machine
Git hooks are scripts in .git/hooks that run at commit and push time — exit non-zero and the operation is cancelled. This guide installs pre-commit, commit-msg and pre-push, and measures them: 9 attempts, 4 blocked, 5 allowed. Includes two real bugs found while testing: git diff --check --quiet and compileall without -f.

Every vibe project has had this moment: a commit sneaks in a line with trailing whitespace, a Python file with an unclosed parenthesis, a commit message that just says "whatever" — and nobody notices until the code is pushed, a teammate pulls it, and CI turns red, only to trace the problem back to your own machine. Git hooks exist to solve exactly this: they are scripts placed in the .git/hooks/ directory that run automatically at key moments — committing, pushing — and if a check fails, the operation is cancelled outright, so the bad code never leaves your machine. In the age of AI-written code, the need is more urgent than before: an agent can generate hundreds of lines at once, faster than any human, and the trailing whitespace, unclosed brackets, and leftover debug prints come along for the ride; checking line by line by hand can no longer keep up, so there has to be an automatic gate before code leaves your machine. Hooks are that gate — they do not care about language or model, only about the exit code: 0 lets it through, non-zero blocks it. This guide explains the three most useful hooks with git 2.43.0 — pre-commit, commit-msg, and pre-push — from installation, writing the scripts, and measuring interceptions, to team sharing and common traps. The demo runs in a temporary repo at /tmp/demo243_hooks_repo, driven by demo243_zh.py in the draft directory; the English rerun is rerun_en_demo243_g2.py. Across 9 commit and push attempts, the hooks blocked 4 and allowed 5, with identical numbers in both versions.
What hooks are: which moment they guard
Git's workflow has many "hook points": at every commit, push, and rebase, Git looks for a script with the matching name at a specific moment, runs it if found, and cancels the operation if the script exits non-zero. The five most used client-side hooks are: pre-commit, which runs before the commit message is written and fits checks on the staged content — trailing whitespace, syntax errors, leftover debug print calls; prepare-commit-msg, which runs before the message editor opens and fits automatically adding a template or ticket number to the message; commit-msg, which runs after the message is written but before the commit is recorded, and fits checking the message format; post-commit, which runs after the commit is done and fits sending notifications or logging — it cannot block anything, because the commit already exists; and pre-push, which runs before pushing and fits a full sweep — compiling every file, running fast tests. Server-side hooks exist too (pre-receive, update), but those belong to repository administrators, not personal projects, so this guide skips them. One division of labor is enough to remember: pre-commit asks "is this commit's content clean," commit-msg asks "is this commit's message clear," and pre-push asks "is this batch of commits fit to be seen." Three hooks covering three stretches add up to three gates from your machine to the remote.
Installation: one file, one executable bit
Installing a hook takes two steps. First, create a file with the hook's name in .git/hooks/, such as pre-commit; Git ships a set of .sample example files, and editing one of those is the fastest way in. Second, make it executable: chmod +x .git/hooks/pre-commit. Without the second step, the hook is just a text file and Git skips it — the most common reason beginners find their hook "does nothing," which is why the demo explicitly runs chmod for every hook it installs. Hooks can be written in any language: shell is the most common, because Git passes information as command-line arguments and standard input; Python works too, with #!/usr/bin/env python3 on the first line. What can a hook script see? pre-commit takes no arguments and reads the staged area with git diff --cached; commit-msg receives one argument, the path of the file holding the commit message, which it can read to check the message; pre-push reads four columns from standard input — local ref, local commit, remote ref, remote commit. The exit code is the hook's language: 0 means allow, non-zero means block, and anything printed to standard output or standard error is shown verbatim to the person committing — so when blocking, write clearly why it was blocked and how to fix it, not just an exit code. One easily missed point: hooks run with the repository root as the current directory, so relative paths in scripts are safe; but the environment variables in a hook are not exactly the same as in your interactive shell — when committing from a GUI, for example, the hook may not see the PATH set in your .bashrc, so tools called by scripts should use absolute paths, or the script should set PATH explicitly at the top. The demo hooks only use git and python3, which are normally on PATH — enough for a personal project; for team projects, a defensive PATH line at the top of the hook saves a lot of "works on my machine" arguments.
What a mature pre-commit looks like
The demo's pre-commit has only two checks; real projects usually add three more to make a full combination. First, formatting: run ruff format or black --check for Python, prettier --check for front-end code — block on bad formatting instead of arguing about spaces in code review later. Second, static checks: run ruff check or flake8 over the staged Python files so unused imports and undefined variables surface before the commit. Third, secret scanning: run gitleaks or detect-secrets over the staged area to see whether anyone accidentally wrote an API key or token into the code — once a secret enters commit history, deleting it later still leaves it in the history, and cleaning that up is painful, so it is better to have the hook block it at the door. Those three plus the demo's trailing-whitespace and syntax checks make a solid local defense. Order matters too: run the fast ones first (whitespace, formatting, syntax), then the slow ones (secret scanning, unit tests), and exit as soon as the first one fails instead of waiting for the rest — the less time a person waits on a hook, the less likely they are to bypass it. Many teams write this combination into the pre-commit framework's configuration file, install it with one command, and reuse it across projects — the "team sharing" section below covers that.
Gate one: pre-commit blocks dirty code
The demo's first hook does two things: check trailing whitespace, and check Python syntax. Trailing whitespace uses Git's own check:
if git diff --cached --check; then
:
else
echo "pre-commit: trailing whitespace found, please clean it up"
git diff --cached --check
exit 1
fi
There is a trap here that testing actually hit: the first version was written as git diff --cached --check --quiet, and clean commits were blocked too. The reason is that --quiet means "exit 1 if there is any difference at all," not "exit only on whitespace errors" — whenever the staged area had any content, the condition was true and the hook blocked everything. Dropping --quiet makes git diff --check exit non-zero only when it finds whitespace errors, which is the correct logic. In the demo, the first commit deliberately left three trailing spaces on line one, and the hook blocked it immediately, printing app.py:1: trailing whitespace.; after removing the spaces and committing again, it passed on the first try. The syntax check uses the standard library's compiler:
for f in $(git diff --cached --name-only --diff-filter=ACM | grep '\.py$'); do
python3 -m py_compile "$f" || { echo "pre-commit: $f has a syntax error"; exit 1; }
done
The key is git diff --cached --name-only: it lists only the files "staged for this commit," not everything in the working tree — a file changed halfway but not yet git added is not its business. In the demo, line three was missing a closing parenthesis, and the hook printed SyntaxError: '(' was never closed and blocked it; after the fix, the commit passed. One more detail: py_compile creates a __pycache__ directory next to the file, and in the first run of the demo, git add . swept the .pyc file into the commit — the correct fix is a .gitignore at the repository root containing __pycache__/, which is what the demo does after fixing it. By-products created by the hook itself should not enter version control.

Gate two: commit-msg polices the message
With the code clean, the commit message can still be a mess. Messages like "whatever," "changed stuff," or "fix bug" mean nothing three months later when someone tries to work out what a commit actually did. The demo's commit-msg hook enforces a minimal format: the message must start with a type — feat: (new feature), fix: (bug fix), docs: (documentation), chore: (chores), refactor: (refactoring), test: (tests) — followed by one sentence:
MSG=$(cat "$1")
case "$MSG" in
feat:*|fix:*|docs:*|chore:*|refactor:*|test:*) exit 0 ;;
*) echo "commit-msg: message must start with feat:/fix:/docs:/chore:/refactor:/test:"; exit 1 ;;
esac
The demo first tried "just write anything," and the hook blocked it with the format hint; changed to docs: add README, it passed on the first try. The format itself does not matter much — what matters is the "type" information: with types, you can later filter commits by type, generate a changelog automatically, and tell at a glance which commit fixed a bug and which added a feature when rolling back. Many teams use the full Conventional Commits specification, which builds on the same idea and adds feat! for breaking changes and fix(scope): for the affected area; starting with six types is enough for a personal project. Note what the hook checks: it reads the file at $1, which holds the full commit message; messages written with git commit -m and messages written in an editor go through the same check, with no exceptions.
Gate three: pre-push is the last line of defense
pre-commit only checks "what is staged for this commit," while pre-push checks "everything about to leave." The demo's pre-push hook compiles every Python file before pushing:
python3 -m compileall -q -f . || { echo "pre-push: a Python file failed to compile"; exit 1; }
To demonstrate this gate, the script deliberately commits a broken file into local history with git commit --no-verify — --no-verify skips pre-commit and commit-msg, a back door Git leaves for emergencies that should not be used routinely. The broken file entered local history, and on push, pre-push blocked it; after fixing the file, committing again, and pushing again, it passed on the first try. Two lessons from live testing deserve their own mention here. The first is the -f flag on compileall: the first version of the demo hook omitted -f, and the broken file's push unexpectedly went through. The investigation found that the repository had previously committed a __pycache__/app.cpython-312.pyc, and the broken file and the good file were written within the same second — the modification time recorded in the .pyc header has one-second granularity, so a file changed within the same second is misjudged as "unchanged," compileall skips compiling it, and the broken file slips through. Adding -f to force recompilation made the problem disappear. The second lesson has the same root cause: __pycache__ should never enter version control in the first place — putting it in .gitignore avoids this misjudgment and keeps build artifacts out of commits. The two lessons together make one sentence: hooks must guard not only against dirty code, but against their own blind spots.
Beyond compile checks, pre-push can also hold the genuinely "last gate" items: running the fast unit tests, confirming the local branch has not fallen too far behind the remote main branch, or checking that no oversized files are in the push — if someone accidentally git added a few hundred megabytes of data files or model weights, pushing them slows down everyone's clones, and blocking that at the door is far cheaper than cleaning history afterwards. The principle is the same as for pre-commit: only include checks where failure means "this definitely should not go out," not "nice to have" checks — otherwise a push takes minutes and people will bypass the hook sooner or later. Remember what pre-push is: the last door before code leaves your machine, beyond which lies remote history that everyone can see, so a few extra seconds here are worth it.
Hooks vs CI: fast locally, thorough remotely
Hooks are not a replacement for CI, and the division of labor must be clear. Hooks run on your machine and run "fast checks": trailing whitespace, syntax, message format, quick unit tests, aiming for results within seconds — a hook that takes more than 10 seconds will push people to --no-verify around it, and then the hook is as good as gone. CI runs remotely and runs "full checks": the complete test suite, type checking, coverage, security scans, where taking minutes is fine. The demo's three hooks all finish within 1 second — that is how a hook should feel. Another common misconception is thinking hooks mean CI is unnecessary. Hooks only guard your own machine; if teammates have not installed the same hooks, dirty code can still be pushed — hooks are not versioned by default, which is the next problem. The reverse is equally true: relying only on CI without hooks stretches the feedback loop to "commit — push — wait for CI — come back and fix," so a trailing space has to travel the whole pipeline before being found, and fixing it then costs more than being blocked locally. The right setup is two layers doing their own jobs: local hooks give "second-level feedback, blocking low-level mistakes," and remote CI gives "full verification, guarding the merge baseline"; only code that passes both layers deserves to enter the main branch.
Team sharing: hooks are not versioned by default
This is Git hooks' biggest trap: the .git/hooks/ directory itself is not under version control, so the hooks you carefully wrote do not come down when a teammate runs git clone. There are three fixes. The first is to version the hook scripts inside the repository, for example at scripts/hooks/pre-commit, plus a scripts/setup-hooks.sh that new members run once after cloning to copy or symlink the scripts into .git/hooks/ and add the executable bit; the README should say "run this script after cloning." The second is Git's built-in core.hooksPath setting: git config core.hooksPath scripts/hooks tells Git to look for hooks directly in the repository directory, skipping the copy step — but that setting is itself local, so everyone has to run it once. The third is a ready-made hook management framework, most commonly pre-commit (the Python framework, not the hook name): a .pre-commit-config.yaml at the repository root declares which checks to run (trailing whitespace, end-of-file newlines, Python formatting), members run pre-commit install once, and the setup is reusable across projects. A personal project can start with the first approach: scripts in the repo, a setup script, one line in the README. A team project should go straight to the third — it saves everyone maintaining their own scripts.
The five traps beginners fall into
Trap one: the hook has no executable bit — chmod +x is part of installation, not optional; after installing, deliberately commit dirty code once to see whether the hook blocks it before starting real work. Trap two: checking the wrong thing — pre-commit must use git diff --cached to see the staged area, while git diff sees the working tree, so a half-staged file gets misjudged; conversely, pre-push must check all files, not just the staged area. Trap three: --no-verify becomes a habit — bypassing once in an emergency is fine, bypassing three times makes the hook decorative; if a check cannot be passed, fix the hook first, then commit, instead of going around the hook. Trap four: hooks that run too slowly — stuffing the full test suite into pre-commit makes every commit wait a minute, and people will delete the hook sooner or later; heavy checks belong in pre-push or CI, and local hooks should only do second-level checks. Trap five: the hook script itself has a bug — hooks are code too, and they need testing; the --quiet misjudgment and the missing -f on compileall in this demo were both bugs in the hooks themselves, and fixing a hook works the same way as fixing business code: reproduce first, then change, then re-run the demo to confirm it blocks what it should and allows what it should.
Summary and checklist
In one sentence: Git hooks are scripts in .git/hooks/ that run automatically at the key moments of committing and pushing, deciding allow or block by exit code — pre-commit asks whether this commit's content is clean, commit-msg asks whether this commit's message is clear, and pre-push asks whether this batch of commits is fit to be seen. After this guide, check yourself against this list: can you install a hook in .git/hooks/ and add the executable bit? Can you write a pre-commit that blocks trailing whitespace with git diff --cached --check? Can you explain the difference between git diff and git diff --cached? Can you write a commit-msg that enforces a message format? Can you say which two hooks --no-verify skips? Can you say why compileall needs -f? Do you know why hooks are not versioned by default, and the three ways to share them? Do you know what local hooks and remote CI should each guard, and why the feedback loop cannot rely on CI alone? If all of those are yes, Git hooks are truly in hand. The best next exercise is to install these three hooks in your own vibe project: copy the three scripts from the demo verbatim, run through a commit to confirm they block and allow as expected, then move the scripts into scripts/hooks/ in the repository and add one line to the README — "run the setup script after cloning." After installing, deliberately commit dirty code once, watch the hook block it with your own eyes, then fix it and commit again — only after triggering an interception yourself do you truly own the defense. The full demo code is in the draft directory as demo243_zh.py, and the English rerun is rerun_en_demo243_g2.py; across 9 attempts the hooks blocked 4 (pre-commit 2, commit-msg 1, pre-push 1) and allowed 5, with identical numbers in both versions.
Boundary with published guides: this guide covers Git hook automation (installing, scripting, and sharing pre-commit, commit-msg, and pre-push), not branching and rebasing (covered in the Git branch-rebase-conflict guide), not the full history of commit-message conventions (only the six-type starter version), and not building CI pipelines (only the division of labor between hooks and CI). Each guide covers its own stretch, with no overlap.
Comments (0)
Sources
Related articles
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
6 files, 24 lines, 4 TODO lines; false | true gives PIPESTATUS 1 and 0, pipefail on exits 1, off exits 0; a spaced filename splits into 2 words unquoted, 1 quoted; backup 6 files, 445 bytes. Bash 5.2.21, measured.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.