Sub topic 2
Client-side hooks and when Git runs them
This chapter assumes you know the basic Git workflow (add, commit, push) and the difference between the staging area and the working tree. You should also be comfortable writing a short shell script. It covers the client-side hooks, the order in which Git calls them, and which of them can stop an operation. The next chapters cover executable bits and exit status in more detail, and then writing a pre-commit hook.
Client-side and server-side hooks
A Git hook is an executable file that Git runs at a fixed point in a command. Hooks fall into two groups:
- Client-side hooks run on your machine. Commands such as
git commit,git merge,git pushandgit checkouttrigger them. - Server-side hooks run on the machine that receives a push, for example
pre-receive,updateandpost-receive. Hosting services usually do not let you install your own, and this tutorial does not cover them.
A client-side hook only protects the repository clone it is installed in. Hooks are not part of the repository's history, so git clone does not copy them. Each developer has to install them, and each developer can skip them. Later chapters cover sharing hooks and why CI is still needed.
Where Git looks for hooks
Git looks for hooks in the directory named by the core.hooksPath setting. If the setting is unset, it uses .git/hooks. A new repository gets sample files there, named like pre-commit.sample. Git ignores them because of the .sample suffix.
A hook is found by its exact name. Git runs .git/hooks/pre-commit, and it does not run pre-commit.sh or Pre-Commit.
git config --get core.hooksPath
git rev-parse --git-path hooksThe second command prints the directory Git will actually use, which is the quickest way to check where to put a file.
The commit sequence
The commit hooks run in a fixed order. This is the order for a normal git commit:
Each hook has a distinct job:
pre-commitruns first, before Git asks for a message. It inspects what is about to be committed. A non-zero exit aborts the commit.prepare-commit-msgruns after Git builds the default message and before the editor opens. It can edit the message file, for example to add a branch name or a template. A non-zero exit aborts the commit.commit-msgruns after you finish the message. It validates the message. A non-zero exit aborts the commit.post-commitruns after the commit exists. It cannot change the outcome, so it suits notifications or logging.
Arguments that matter
Hooks receive information as command-line arguments, and some also receive data on standard input.
| Hook | Arguments |
|---|---|
| `pre-commit` | none |
| `prepare-commit-msg` | message file path, message source (`message`, `template`, `merge`, `squash` or `commit`), and a commit hash when you amend or reuse a commit |
| `commit-msg` | message file path |
| `post-commit` | none |
The message file is usually .git/COMMIT_EDITMSG. A hook that wants to change the message must edit that file in place. Printing a new message to standard output has no effect.
Hooks for other operations
Commits are the most common trigger, but several other commands call hooks.
| Hook | When it runs | Can abort the operation? |
|---|---|---|
| `pre-merge-commit` | A merge succeeded and is about to be committed, before the message editor | Yes |
| `post-merge` | After a merge finishes, including a fast-forward merge | No |
| `pre-rebase` | Before `git rebase` starts | Yes |
| `post-rewrite` | After `git commit --amend` or `git rebase` replaces commits | No |
| `post-checkout` | After `git checkout` or `git switch` updates the working tree, and after `git clone` | No |
| `pre-push` | After the remote is contacted, before any objects are sent | Yes |
| `pre-auto-gc` | Before Git runs automatic garbage collection | Yes |
"Cannot abort" means that the work is already done and the hook's exit code does not undo it. One detail: for post-checkout, the hook's exit status becomes the exit status of git checkout or git switch. The checkout still happens, but a script that checks the exit status will see a failure.
Git also has hooks for the e-mail patch workflow (applypatch-msg, pre-applypatch, post-applypatch and sendemail-validate). Teams that do not apply patches from mailing lists can ignore them.
Details worth knowing
- A fast-forward merge creates no commit, so
pre-commit,commit-msgandpre-merge-commitdo not run.post-mergedoes run. Sincegit pullis a fetch followed by a merge, it triggerspost-mergetoo. - If a merge stops on a conflict, you resolve it and run
git commit. That commit runs the normal commit hooks, withprepare-commit-msgreceiving the sourcemerge. git rebasereplays commits without runningpre-commitfor each one. Afterwards it runspost-rewrite. A bad commit that passes through a rebase is not rechecked.git commit --amenddoes runpre-commit, because it creates a new commit.
Which hooks stop an operation
Only hooks that run before the point of no return can stop an operation. Hooks such as post-commit, post-merge and post-rewrite run too late to change the outcome.
In the pre-commit family, the rule is simple: exit status 0 lets Git continue, and any non-zero status aborts the operation. The hook's output goes to the terminal, so write failure messages to standard error and say what to fix.
Seeing the order for yourself
The most reliable way to learn the sequence is to watch it. This script prints its own name and arguments, then exits successfully. Because it always exits 0, it never blocks anything.
#!/bin/sh
# trace-hook: report which hook ran and with what arguments.
name=$(basename "$0")
echo "hook: $name args: $*" >&2
exit 0Save it as trace-hook in a scratch repository, then install a copy under each hook name:
for h in pre-commit prepare-commit-msg commit-msg post-commit pre-push; do
install -m 755 trace-hook ".git/hooks/$h"
done
echo "hello" > note.txt
git add note.txt
git commit -m "Try the hooks"The output should look like this:
hook: pre-commit args:
hook: prepare-commit-msg args: .git/COMMIT_EDITMSG message
hook: commit-msg args: .git/COMMIT_EDITMSG
hook: post-commit args: Run git commit without -m and prepare-commit-msg shows the source template or no source argument, depending on your configuration. Run git commit --amend and the third argument becomes HEAD. Run git commit --no-verify and the pre-commit and commit-msg lines disappear while the other two stay.
install -m 755 sets the executable bit when it copies the file. A hook without that bit does not run. In recent Git versions you will see a hint such as The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.
The environment a hook runs in
Git sets up the environment for each hook, and a few facts matter when you write your own:
- The working directory is the top of the working tree for a normal repository, so relative paths in a hook resolve from the repository root.
- Git sets variables such as
GIT_DIR. During a commit it may also setGIT_INDEX_FILE. - When you run
git commit -aorgit commit path/to/file, Git builds a temporary index and pointsGIT_INDEX_FILEat it. A hook that runsgit diff --cachedsees the right data because Git reads that variable. A hook that opens.git/indexdirectly sees the wrong data. Use Git commands and never parse the index yourself. - A hook that runs
gitinside another repository, for example in a submodule, may need to unset these variables first. Otherwise the inner commands act on the outer repository.
A pre-push example with standard input
pre-push is the one commonly used client-side hook that gets data on standard input. Git passes the remote name and URL as arguments. For every ref being pushed it writes one line to standard input, in the form <local ref> <local oid> <remote ref> <remote oid>.
#!/bin/sh
# .git/hooks/pre-push
remote="$1"
url="$2"
zero="0000000000000000000000000000000000000000"
while read -r local_ref local_oid remote_ref remote_oid; do
if [ "$local_oid" = "$zero" ]; then
echo "pre-push: deleting $remote_ref on $remote ($url)" >&2
else
echo "pre-push: sending $local_ref to $remote_ref on $remote" >&2
fi
done
exit 0Deleting a remote branch shows up as a line whose local object ID is all zeros. A new remote branch has all zeros in the remote object ID column. The zero string above has 40 characters for SHA-1 repositories. A repository that uses SHA-256 has 64-character IDs, so a portable hook should test for "all zeros" and not compare against a fixed string.
Choosing a stage for a check
The stage decides how often a check runs and how much it costs when it fails.
| Stage | Runs | Good for |
|---|---|---|
| `pre-commit` | Every commit | Fast checks on staged files, such as whitespace, formatting and linting |
| `commit-msg` | Every commit | Message format |
| `pre-push` | Once per push | Slower checks, such as the unit test suite |
| CI | Every push or pull request, on a shared machine | Everything that must be enforced |
A check that takes thirty seconds in pre-commit encourages people to use --no-verify. The same check in pre-push costs that time once for several commits. Later chapters return to this trade-off.
Common mistakes
- The hook never runs. Check the file name (no extension), the executable bit, and
git config core.hooksPath. Ifcore.hooksPathpoints elsewhere,.git/hooksis ignored. - The hook runs but never blocks. The script ended with a command that returned
0. A shell script exits with the status of its last command. End with an explicitexit 1on failure. - A post-hook is used as a gate.
post-commitandpost-mergecannot undo anything. - The shebang is wrong. A first line like
#!/bin/bashfails where bash lives elsewhere, and#!/bin/shdoes not give you bash features. Choose the interpreter on purpose. - A hook expects interactive input. Commits made from an editor or a GUI may have no terminal, so a hook that prompts with
readcan hang or fail.
Exercise
You run git commit -m "Fix typo" --no-verify. Which of pre-commit, prepare-commit-msg, commit-msg and post-commit still run?
Show answer
prepare-commit-msg and post-commit still run. --no-verify skips only pre-commit and commit-msg.
Exercise
A teammate fast-forwards their branch with git pull. A pre-commit hook and a post-merge hook are both installed. Which one runs, and why?
Show answer
Only post-merge runs. A fast-forward merge moves the branch pointer without creating a commit, so the commit hooks do not run, but Git still reports the merge as finished and calls post-merge.
Exercise
You installed an executable .git/hooks/pre-commit that exits 1 on a failure, but commits still go through. core.hooksPath is set to .githooks. What is the cause and the fix?
Show answer
When core.hooksPath is set, Git ignores .git/hooks and looks only in .githooks. Move the hook into .githooks (or unset core.hooksPath), and make sure the file is executable.