Sub topic 10
Keeping Hooks Fast and Choosing the Right Stage
This chapter assumes you can write a basic pre-commit hook, that you know hooks are executable files whose exit status decides whether Git continues, and that you understand the difference between the index and the working tree. It also assumes you know that --no-verify skips hooks. Here you will learn how to keep hooks quick and how to decide which check belongs in pre-commit, pre-push or CI.
Why speed is a correctness property
A hook that takes 40 seconds does not get run 40 seconds' worth of times. People learn to type git commit --no-verify, and then the hook protects nobody. Developers also commit in small steps, so a slow pre-commit hook discourages exactly the habit you want.
A workable budget for each stage:
| Stage | Runs when | Time budget | Good for |
|---|---|---|---|
| `pre-commit` | Before each commit is created | Under about 2 seconds, 5 at most | Whitespace, formatting, lint on changed files, secret scans |
| `commit-msg` | After the message is written | Effectively instant | Message format |
| `pre-push` | Before objects are sent to a remote | Tens of seconds to a few minutes | Unit tests, type checks, build checks |
| CI | After the push, on a server | Minutes to hours | Full test suite, integration tests, platform matrix, anything authoritative |
These numbers are rules of thumb. The principle is that the more often a stage runs, the cheaper its checks must be.
Scope: check only what changed
The biggest speed gain comes from checking only the files in the commit. Running a linter over the whole repository costs time proportional to the repository size. Running it over the staged files costs time proportional to the change.
Ask Git for the staged paths with git diff --cached --name-only. Add --diff-filter=ACM to keep only added, copied and modified files. Without it, deleted files appear in the list, and a tool that tries to open them fails.
The shellcheck example in the staged-content chapter used for f in $(...), which splits on whitespace and breaks on file names with spaces. A sturdier form uses NUL-separated output (-z) and xargs -0:
#!/bin/sh
# .githooks/pre-commit
# Lint staged shell scripts in one shellcheck process.
# Exit early when no shell script is staged. This avoids starting any tools.
if [ -z "$(git diff --cached --name-only --diff-filter=ACM -- '*.sh')" ]; then
exit 0
fi
git diff --cached --name-only -z --diff-filter=ACM -- '*.sh' | xargs -0 shellcheckThree things make this fast:
- Early exit. A commit that touches no
.shfile costs onegit diff. - One process for many files. Starting
shellcheckonce for ten files is cheaper than starting it ten times. - No empty-input run. The
-zform is safe because the hook returns beforexargswhen nothing matches. This avoidsxargs -r, which GNUxargssupports but older BSD versions may not.
The exit status of a pipeline is the status of its last command. Here that is xargs, which returns non-zero if any shellcheck invocation fails, so the hook blocks the commit.
Measure before you optimize
Run the hook directly and time it. Git runs pre-commit from the top of the working tree, so run it from there too:
cd "$(git rev-parse --show-toplevel)"
git add -u
time .githooks/pre-commitIf the hook is slower than your budget, find out which line costs the most. Add set -x temporarily to see each command as it runs, or wrap individual commands in time. Common causes:
- Starting a heavy runtime (a JVM, a large Node project) for a trivial check.
- Running a type checker or test suite on every commit.
- Network calls, such as downloading rules or contacting an API.
- Calling
git statusorgit ls-fileson a huge repository more than once.
Techniques that keep a hook fast
- Order checks from cheapest to most expensive. If the whitespace check fails in 20 ms, there is no point waiting for a 3-second linter first.
- Fail fast, or run independent checks in parallel. Failing fast stops at the first error. Running in parallel reports all errors at once, which saves round trips.
- Use incremental tools. Many linters offer a cache (for example
eslint --cache). Caches keyed by file content make unchanged files free. - Skip irrelevant work. Match on path patterns and exit early, as shown above.
- Avoid the network. A hook that needs the internet fails on planes and is slow on bad connections.
Here is a hook that runs two independent checks in parallel and combines their results:
#!/bin/sh
# .githooks/pre-commit
# Run independent checks concurrently, then fail if either failed.
check_whitespace() {
git diff --cached --check
}
check_markers() {
# Fail if a staged added line contains the text DO NOT COMMIT.
if git diff --cached -U0 | grep -n '^+.*DO NOT COMMIT'; then
echo "pre-commit: remove the DO NOT COMMIT marker." >&2
return 1
fi
return 0
}
check_whitespace &
pid_whitespace=$!
check_markers &
pid_markers=$!
status=0
wait "$pid_whitespace" || status=1
wait "$pid_markers" || status=1
exit $statuswait PID returns the exit status of that background job, so each failure is recorded. Parallel checks have two limits. Their output can interleave, and checks that write to the index or to files must not run at the same time. Keep parallel checks read-only. For two checks that each take milliseconds, parallelism adds complexity for no gain. Use it when each check takes noticeable time.
Auto-fixing hooks
A formatter that rewrites files inside pre-commit creates a trap. The commit is built from the index, so the formatter's changes land in the working tree only. The commit still contains the unformatted version. Safe options:
- Run the formatter in check mode and fail with a message telling the developer to run the formatter and re-stage.
- Have the hook re-run
git addon the files it changed. This is only safe when the file was fully staged, otherwise you silently stage unrelated edits. - Use a hook manager that handles this case for you.
Choosing the right stage
Ask four questions about a check:
- How long does it take? Over a few seconds rules out
pre-commit. - Does it need only the changed files? If it needs the whole project (type checking, most test suites), it belongs later.
- Can the developer fix it right now, and is the signal unambiguous? Formatting and secret detection fit. Flaky tests do not, because they block unrelated commits.
- Must it be enforced? If yes, it must also run in CI. A hook is only a convenience.
What pre-push receives
pre-push is the natural home for checks that take longer than a commit can afford. Git calls it with two arguments, the remote name and the remote URL. It also writes one line per ref being pushed to standard input, in the form <local ref> <local object name> <remote ref> <remote object name>.
#!/bin/sh
# .githooks/pre-push
# $1 is the remote name and $2 is its URL.
# Stdin has one line per ref: <local ref> <local oid> <remote ref> <remote oid>.
needs_tests=no
while read -r local_ref local_oid remote_ref remote_oid; do
case $local_oid in
*[!0]*) needs_tests=yes ;; # Not all zeros, so a real commit is being pushed.
*) ;; # All zeros means a branch deletion. Nothing to test.
esac
done
if [ "$needs_tests" = yes ]; then
echo "pre-push: running unit tests before pushing to $1..." >&2
make test || exit 1
fi
exit 0The all-zeros test works for both SHA-1 and SHA-256 repositories, because a deletion uses a null object name of whatever length the repository uses. Deleting a remote branch with git push origin --delete topic would otherwise trigger a pointless test run.
pre-push has its own trade-off. It runs only on pushes, so a developer who commits ten times pays once. The failure also arrives later, after more work is piled on top of the broken commit. Keep the check to something a developer can reasonably wait for. If it takes more than a couple of minutes, move it to CI.
Assigning stages in a hook manager
If you use the pre-commit framework, you assign a stage per hook in the configuration. The stages key chooses when each hook runs:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- repo: local
hooks:
- id: unit-tests
name: unit tests
entry: make test
language: system
pass_filenames: false
stages: [pre-push]The framework installs only the stages you ask for. Install both with:
pre-commit install --hook-type pre-commit --hook-type pre-pushForgetting --hook-type pre-push is a common reason the push hook never runs.
Failure modes to expect
- Hook creep. Each added check seems cheap. Re-time the hook every few months and move or remove what has grown.
- Flaky checks. A check that sometimes fails for no reason teaches people to bypass. Move it out of the blocking path.
- Different results locally and in CI. If hooks use different tool versions than CI, a commit passes locally and fails remotely. Pin versions, which is what the
rev:field does in the framework's configuration. - Large commits. A commit of 2,000 files can take far longer than the typical one. Tools that accept many paths in one process cope better than per-file loops.
Exercise
A team's pre-commit hook runs the full unit test suite (about 90 seconds) and a formatter check (about 1 second). Developers have started using --no-verify. Which change would you make, and why must the change not be the only protection for the tests?
Show answer
Move the unit tests out of pre-commit. Run them in pre-push (or only in CI if 90 seconds is too long for a push), and keep the 1-second formatter check in pre-commit, scoped to staged files. Commits then stay fast, so the habit of bypassing fades. The tests must also run in CI, because both pre-push and pre-commit can be skipped with --no-verify or by not installing the hooks, so only CI can guarantee that the tests ran.
Exercise
Your pre-push hook runs make test whenever it is called. A developer runs git push origin --delete old-branch and the tests run anyway. What in the hook's input lets you detect this case, and how do you skip it?
Show answer
For each ref being pushed, Git writes a line to standard input with the local object name in the second field. For a deletion, that field is all zeros. Read the lines with while read -r local_ref local_oid remote_ref remote_oid, and skip any line where $local_oid contains no character other than 0 (for example with case $local_oid in *[!0]*) ... esac). Run make test only when at least one ref has a real object name.