Hooks: Automating Checks Before You Commit
Write a pre-commit and a commit-msg hook, see them refuse bad commits, learn how to share them, and why they are only a safety net.
In this lesson you will
- Explain what a hook is
- Write a pre-commit and a commit-msg hook
- Share hooks with a folder and a setting
- Know the limits of hooks
About 30 minutes
A check that cannot be forgotten
Dev keeps committing a half finished note that starts with TODO, and the other volunteers keep finding it in the published plan. Asking people to be careful has not worked. A better answer is to make the computer check, every time, before the commit is allowed. Git has a place for exactly that: hooks, small scripts that Git runs at set moments, such as just before a commit is made.
Hooks in one paragraph
A hook is an ordinary program, often a short shell script, with a fixed name. If the program exits with a failure code, Git stops what it was doing. The pre-commit hook runs before a commit is created and can refuse it. The commit-msg hook runs after you write a message and can refuse that. There are others, for push, merge and so on. By default, hooks live in .git/hooks, which has a problem you will see below. A neater way is to keep them in a normal folder in the project and tell Git where it is with the core.hooksPath setting.
The session builds two hooks line by line, so every character is visible. The first looks at the staged changes to text files and refuses the commit if a new line contains the word TODO. The second takes the commit message file, measures the first line, and refuses if it is longer than fifty characters.
$ mkdir garden-notes
$ cd garden-notes
$ git init
Initialized empty Git repository in /home/nia/garden-notes/.git/
$ mkdir .githooks
$ echo '#!/bin/sh' > .githooks/pre-commit
$ echo 'if git diff --cached -- "*.txt" | grep -q "^+.*TODO"; then' >> .githooks/pre-commit
$ echo ' echo "pre-commit: remove the TODO lines first"' >> .githooks/pre-commit
$ echo ' exit 1' >> .githooks/pre-commit
$ echo 'fi' >> .githooks/pre-commit
$ echo '#!/bin/sh' > .githooks/commit-msg
$ echo 'subject=$(head -n 1 "$1")' >> .githooks/commit-msg
$ echo 'if [ ${#subject} -gt 50 ]; then' >> .githooks/commit-msg
$ echo ' echo "commit-msg: subject is over 50 characters"' >> .githooks/commit-msg
$ echo ' exit 1' >> .githooks/commit-msg
$ echo 'fi' >> .githooks/commit-msg
$ chmod +x .githooks/pre-commit .githooks/commit-msg
$ git config core.hooksPath .githooks
$ cat .githooks/pre-commit
#!/bin/sh
if git diff --cached -- "*.txt" | grep -q "^+.*TODO"; then
echo "pre-commit: remove the TODO lines first"
exit 1
fi
Watching them work
Now the session tries four commits. The first has a TODO line and is refused, with the hook’s own message. The second removes the TODO but uses a very long message, and is refused by the other hook. The third is clean and works. The fourth adds a TODO again and passes only because it uses --no-verify, which skips the hooks. The log at the end shows 2 commits: the two that were allowed. The refused ones left nothing behind.
$ echo "Beans: row 1" > plan.txt
$ echo "TODO: add carrots" >> plan.txt
$ git add .
$ git commit -m "Add plan"
pre-commit: remove the TODO lines first
$ sed -i '/TODO/d' plan.txt
$ git add plan.txt
$ git commit -m "Add the planting plan with a very long subject that goes on and on"
commit-msg: subject is over 50 characters
$ git commit -m "Add the planting plan"
[main (root-commit) 304bc9f] Add the planting plan
3 files changed, 12 insertions(+)
create mode 100755 .githooks/commit-msg
create mode 100755 .githooks/pre-commit
create mode 100644 plan.txt
$ echo "TODO: later" >> plan.txt
$ git commit -am "Add a note" --no-verify
[main 9fa8bd3] Add a note
1 file changed, 1 insertion(+)
$ git log --oneline
9fa8bd3 Add a note
304bc9f Add the planting plan
Notice what the bypass means. A hook is a safety net for honest mistakes, not a lock against a determined person. Anyone can skip it, so a hook never replaces a check on the server side, such as the protected branch rules from lesson 18.
The catch: hooks do not travel by themselves
The hook files were committed, so a clone receives them. But the core.hooksPath setting lives in a person’s own configuration, which is never cloned. The next session clones the project. The hook files are there, but asking for the setting prints nothing. Until the new person sets it, the hooks do nothing. That is why many teams add one line to their contributing notes, or a small setup script, saying “run this command after you clone”.
$ cd ..
$ git clone -q garden-notes copy
$ cd copy
$ ls .githooks
commit-msg
pre-commit
$ git config core.hooksPath
$ git config core.hooksPath .githooks
$ git config core.hooksPath
.githooks
What makes a good hook
- Fast. A slow hook makes people use the bypass.
- Clear. The message says what is wrong and what to do.
- Narrow. It checks one thing well, such as a leftover note or a secret pattern.
- Documented. Everyone knows how to install it and how to run the same check by hand.
Writing a hook that matches its own text. The first version of the TODO hook searched every staged file, including itself, and refused to be committed. Limiting the check to text files fixed it.
The hook scripts are tiny teaching examples written for a Unix style shell. Hook behaviour and the way Windows runs shell scripts can differ by setup, so test your hooks on the systems your team uses. Hooks are not a security boundary.
Practice for this lesson
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a Git hook?
- A kind of branch
- A small script Git runs at a set moment, such as before a commit
- A remote address
- A merge strategy
The pre-commit hook ran before each commit.
What makes a hook refuse an action?
- The script prints a long message
- The file name is long
- The folder is hidden
- The script exits with a failure code
Both hooks printed a message and exited with failure.
What does git commit –no-verify do?
- Signs the commit
- Skips the pre-commit and commit-msg hooks
- Pushes the commit
- Deletes the hooks
The fourth commit passed with a TODO line only because of it.
Why did the clone not run the hooks?
- The hook files were deleted
- Clones cannot use hooks
- The branch was wrong
- The hooks path setting is local and is not cloned
Asking for the setting printed nothing until it was set.
Why is a hook not enough to protect a main branch?
- Anyone can bypass it, so server side rules are still needed
- Hooks are too slow
- Hooks only work on Mondays
- Hooks cannot read files
A hook is a safety net for honest mistakes.
Summary
- A hook is a script Git runs at a set moment, and a failure code stops the action.
- Keep hooks in a folder and point core.hooksPath at it.
- The setting is not cloned, so new people must run one command.
- Hooks can be bypassed, so they never replace server side rules.
Questions
Do hooks work the same on Windows?
Git for Windows includes a shell that can run simple hook scripts, but setups differ. Test on every system your team uses.
Can a hook change my files?
Yes. Some hooks format code automatically. Be careful with hooks that rewrite files, and make sure people know what they do.
Where do the sample hooks come from?
New repositories include sample hook files inside the hooks folder, with names ending in sample. They show the arguments each hook receives.
