Sub topic 11
Running heavier checks with pre-push
This chapter assumes you can write a basic shell hook, know how exit status decides whether Git proceeds, and have set up core.hooksPath as covered in earlier chapters. Here you will learn what pre-push receives, how to use that information, and which checks belong at this stage.
Why a second gate exists
A pre-commit hook runs on every commit, so it has to be fast. If it takes more than a few seconds, people start using --no-verify. But some checks are valuable and slow: the full unit test suite, a type check of the whole project, a build, or a scan of dependencies.
pre-push is the natural home for these. You push far less often than you commit, and a push is the moment your work leaves your machine. A failure there costs less than a failed CI run, and it costs your teammates nothing.
When Git runs pre-push
Git runs pre-push during git push. The documented order is: Git contacts the remote and checks its state, then runs the hook, then sends objects. The hook can stop the push, but it cannot change what gets pushed.
What the hook receives
The hook gets two arguments and one stream of input:
$1is the name of the remote, such asorigin. If you push to a bare URL, this is the URL.$2is the remote's URL.- Standard input has one line per ref being pushed, in this format:
<local ref> <local object name> <remote ref> <remote object name>
A push of main to an existing remote branch looks like this:
refs/heads/main 9f2c1ab... refs/heads/main 41d7e03...Two special values matter:
| Situation | What you see |
|---|---|
| New branch on the remote | The remote object name is all zeros |
| Deleting a remote branch | The local ref is `(delete)` and the local object name is all zeros |
The all-zero value has the same length as your repository's hash (40 characters for SHA-1, 64 for SHA-256). Don't hard-code the length. The sample hook shipped with Git derives it with git hash-object, and the examples below do the same.
Because the hook sees both ends of each ref, it can work out exactly which commits are about to leave your machine. A pre-commit hook cannot do that.
Example: reject unfinished commits
A cheap and useful pre-push check scans the outgoing commit messages for markers such as WIP or fixup!. Pushing those usually means you forgot to clean up your history.
#!/bin/sh
# .githooks/pre-push
# Refuse to push commits whose subject starts with WIP, fixup! or squash!.
remote="$1"
zero=$(git hash-object --stdin </dev/null | tr '0-9a-f' '0')
status=0
while read -r local_ref local_oid remote_ref remote_oid; do
# Deleting a remote branch sends no commits, so there is nothing to check.
if [ "$local_oid" = "$zero" ]; then
continue
fi
if [ "$remote_oid" = "$zero" ]; then
# New branch: check commits that no remote-tracking branch of this remote has.
commits=$(git rev-list "$local_oid" --not --remotes="$remote")
else
commits=$(git rev-list "$remote_oid..$local_oid")
fi
for c in $commits; do
subject=$(git log -1 --format=%s "$c")
case "$subject" in
WIP*|wip*|fixup!*|squash!*)
echo "pre-push: $local_ref has an unfinished commit: $c $subject" >&2
status=1
;;
esac
done
done
exit $statusThree points in this script are easy to get wrong:
- It reads all of standard input before deciding anything. Git writes the ref lines to a pipe, so you should consume them in one loop.
- It handles three cases explicitly: deletion, new branch and update. The
remote_oid..local_oidrange is only valid when the remote already has the branch. - It collects failures in
statusinstead of exiting on the first one, so the developer sees every problem in one run.
If the remote's old commit is not an ancestor of the new one (a force push), remote_oid..local_oid still lists the commits you are adding. If the remote object isn't present in your local clone, git rev-list can fail. Treat that as a reason to fetch first, not as something to hide.
Example: run tests on the commit being pushed
The obvious pre-push hook is make test. It has a trap, though. Tests run against your working tree, and the working tree may not match what you are pushing. Any of these breaks the assumption:
- You have uncommitted edits, so the tests pass or fail because of code you aren't pushing.
- You run
git push origin other-branchwhile a different branch is checked out. - You push several refs at once.
A safer approach is to check out each pushed commit into a temporary worktree and test it there. git worktree shares the repository's object store, so this is much cheaper than cloning.
#!/bin/sh
# .githooks/pre-push
# Run the test suite against each commit that is about to be pushed.
TEST_CMD="${PRE_PUSH_TEST_CMD:-make test}"
zero=$(git hash-object --stdin </dev/null | tr '0-9a-f' '0')
status=0
while read -r local_ref local_oid remote_ref remote_oid; do
case "$local_ref" in
refs/heads/*) ;; # only test branches
*) continue ;; # skip tags and "(delete)"
esac
if [ "$local_oid" = "$zero" ]; then
continue
fi
tmp=$(mktemp -d) || exit 1
git worktree add --detach "$tmp" "$local_oid" >/dev/null 2>&1 || {
echo "pre-push: could not check out $local_oid" >&2
rm -rf "$tmp"
exit 1
}
echo "pre-push: testing $local_ref at $(git rev-parse --short "$local_oid")" >&2
# </dev/null stops the test command from swallowing the rest of our input.
if ! (cd "$tmp" && sh -c "$TEST_CMD" </dev/null); then
echo "pre-push: tests failed for $local_ref" >&2
status=1
fi
git worktree remove --force "$tmp"
done
exit $statusThe </dev/null on the test command matters. Test runners sometimes read standard input, and if one does, it eats the remaining ref lines. Git would then skip the later refs without any error.
A fresh worktree has no node_modules, virtual environment or build cache. If your tests depend on installed dependencies, either install them in the temporary directory, point to a shared cache, or accept the working-tree approach and document the limitation.
Choosing the right stage
| Stage | Runs | Typical budget | Good for | Weak at |
|---|---|---|---|---|
| `pre-commit` | Every commit | Under a few seconds | Formatting, lint on staged files, whitespace, secrets patterns | Anything slow, anything needing the whole project |
| `commit-msg` | Every commit | Instant | Message format | Anything beyond the message |
| `pre-push` | Every push | Seconds to a few minutes | Full tests, type checks, builds, commit-history rules | Teams that push after every commit |
| CI | Every push or merge request on the server | Minutes | Everything, including slow matrix builds | Feedback time, since it comes after the push |
A practical rule: put a check in the earliest stage where it is both fast enough and accurate enough. Formatting belongs in pre-commit. A full test run belongs in pre-push. A check that needs a database, secrets, or several operating systems belongs in CI only.
Using a hook manager for pre-push
Hook managers install pre-commit by default and need a flag for other stages. With the pre-commit framework, you install the push hook explicitly and mark each hook with its stage:
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: unit-tests
name: unit tests
entry: make test
language: system
pass_filenames: false
always_run: true
stages: [pre-push]pre-commit install --hook-type pre-pushpass_filenames: false tells the framework not to append file names to the command, and always_run: true runs the hook even when no matching files changed. Without those two settings, a project-wide test command is called with a list of files it doesn't expect, or skipped. Husky and lefthook have their own pre-push entries, and their configuration is documented by each tool.
Failure modes and edge cases
- Deleting a branch.
git push origin --delete old-branchstill runs the hook. Your script must not try to test the all-zero object. - Tags.
git push --tagssends lines withrefs/tags/.... Decide whether you want to check them. The test example above skips them. - Multiple refs.
git push --allproduces several lines. Handle each one, and don't assume there is only one. - No new commits. A push of an already-pushed ref may send nothing. Your range may then be empty, and the hook should pass quickly.
- Interactive prompts. Standard input is occupied by the ref list, so a hook that asks a question must read from
/dev/tty. Prefer non-interactive checks. - Time. If the hook takes several minutes, developers will bypass it. Measure it, and move work to CI if it grows.
Debugging a hook that does nothing
If your hook doesn't seem to run, check these in order:
- Run
git config core.hooksPathto see which directory Git is using. If it is set,.git/hooksis ignored. - Confirm the file is named exactly
pre-push, with no extension, and thatls -lshows the executable bit. - Run the hook by hand with a fake input line, for example
printf 'refs/heads/main %s refs/heads/main %s\n' "$(git rev-parse HEAD)" "$(git rev-parse HEAD~1)" | .githooks/pre-push origin url. - Add
set -xnear the top of the script to see each command as it runs.
Exercise
A developer on branch feature runs git push origin hotfix while having uncommitted changes. The pre-push hook runs make test in the repository root. Why can the result be wrong, and what change fixes it?
Show answer
make test runs against the checked-out working tree, which is feature plus the uncommitted edits, not the hotfix commit being pushed. The tests can pass or fail for the wrong code. The fix is to read the pushed commit from the hook's standard input and test that commit in a temporary git worktree (checked out detached at the local object name), then remove the worktree afterwards.
Exercise
Your pre-push script loops over standard input and runs npm test inside the loop. With git push --all, only the first branch is tested. What is the likely cause, and how do you prevent it?
Show answer
npm test (or a process it starts) reads standard input and consumes the remaining ref lines, so the while read loop ends early. Redirect the test command's input with </dev/null, or read all lines into a variable before running any commands.