Sub topic 8
Validating commit messages with commit-msg
This chapter assumes you can write a basic pre-commit hook, know that a hook is an executable file whose exit status decides the outcome, and are comfortable with sh and regular expressions. Here you add a hook that checks the commit message instead of the staged files.
What commit-msg does
The commit-msg hook runs after you have written a message and before Git creates the commit. Git saves the proposed message to a file and runs the hook with that file's path as the first argument ($1). If the hook exits with a non-zero status, Git aborts the commit and nothing is recorded.
Because the message is not part of the staged content, git diff --cached cannot see it. The hook has to read the file it is given.
The hook runs in these cases:
git commit -m "...", after Git writes the message to a file.git commitwithout-m, after you save and close the editor.- Commands that create commits and run the hook, such as
git mergewith a generated message.
It does not run when you use git commit --no-verify.
A first message check
This hook requires the first line to look like type(scope): summary. This is the Conventional Commits style.
#!/bin/sh
# .githooks/commit-msg
# $1 is the path to the file holding the proposed commit message.
if ! head -n 1 "$1" | grep -qE '^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+'; then
echo "commit-msg: the first line must look like 'type(scope): summary'." >&2
exit 1
fiFour details matter here:
head -n 1 "$1"reads only the subject line. The body can be free-form.grep -qEis quiet and uses extended regular expressions. Its exit status drives theif.- The error goes to standard error with
>&2, so it appears in the terminal even when Git captures standard output. - The script has no trailing
exit 0. Theifbody is skipped when the check passes, so the script ends with a status of 0.
Make the file executable and activate it, using the same steps as for any hook:
chmod +x .githooks/commit-msg
git config core.hooksPath .githooksThen try it:
git commit --allow-empty -m "fixed stuff"
# commit-msg: the first line must look like 'type(scope): summary'.
git commit --allow-empty -m "fix(parser): handle empty input"
# [main 3f2a1c9] fix(parser): handle empty inputCommon errors
Checking comment lines. When Git opens an editor, the message file contains lines starting with # (the instructions and status). Git strips them after the hook runs in some configurations. If your hook inspects more than the first line, skip comment lines first, for example with grep -v '^#' "$1". Checking only line 1 avoids the problem, unless the user starts the message with a comment.
Reading the wrong thing. Using git log -1 inside commit-msg shows the previous commit, because the new one does not exist yet. Always read $1.
Forgetting the executable bit. A hook without chmod +x is ignored. Git prints a hint on recent versions but does not fail the commit.
Rejecting generated messages. Merge and revert commits have messages such as Merge branch 'x' or Revert "...". A strict pattern rejects them. Allow them explicitly if your team uses them:
#!/bin/sh
# .githooks/commit-msg
subject=$(head -n 1 "$1")
case "$subject" in
Merge\ *|Revert\ *|fixup!\ *|squash!\ *) exit 0 ;;
esac
if ! printf '%s\n' "$subject" | grep -qE '^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+'; then
echo "commit-msg: the first line must look like 'type(scope): summary'." >&2
exit 1
fiThe case statement exits early for those prefixes. Everything else must match the pattern.
Limits of the check
A message hook is a convenience for the author. It gives fast feedback while the context is still fresh. It cannot enforce anything on its own, because any contributor can skip it with --no-verify or never install it. If the format matters, for example because a tool builds release notes from it, repeat the check in CI against the commits in a pull request.
Exercise
A teammate runs git commit -m "update readme" and the commit goes through, even though .githooks/commit-msg exists with a correct pattern check. Give two likely causes and how you would check each.
Show answer
First, the hook is not executable. Check with ls -l .githooks/commit-msg and fix it with chmod +x. Second, core.hooksPath is not set in that clone, so Git looks in .git/hooks instead. Check with git config core.hooksPath and set it to .githooks. A third possibility is that they used --no-verify.
Exercise
Why does a commit-msg hook that runs git log -1 --format=%s to read the subject validate the wrong text?
Show answer
The hook runs before the new commit exists, so git log -1 returns the previous commit's subject. The proposed message is only in the file whose path Git passes as $1.