brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a commit-msg hook can refuse commits whose message breaks your rules

Commit
~/tips/tip-git-commit-msg-hook

if ! head -n1 "$1" | grep -qE '^[A-Z]'; then

Runs a script on every commit message and cancels the commit when the script exits with an error.

Commit messages are the part of a repository people take the least care of. A commit-msg hook is a small script that checks the message before the commit exists. It is the cheapest way to get a rule like a capital first letter, a ticket number or a length limit enforced.

Git calls .git/hooks/commit-msg with one argument: the name of the file that holds the proposed message. If the script exits with a non-zero status, the commit is aborted. Make it executable, or Git ignores it.

#!/bin/sh
if ! head -n1 "$1" | grep -qE '^[A-Z]'; then
  echo "commit-msg: start the subject with a capital letter" >&2
  exit 1
fi
chmod +x .git/hooks/commit-msg

In a test repository, a commit with the subject lowercase subject prints the error message and Git exits with status 1. A commit with Capital subject goes through.

The docs add that the hook may also edit the message file in place, so it can normalize the message into a project format instead of rejecting it. For example, it could append a line to the file.

Two caveats. First, git commit --no-verify skips this hook, so it is a guard rail, not a lock. With --no-verify the bad message gets in without a word. Second, the hook lives in .git/hooks, which is not part of the repository. Your colleagues will not get it by cloning. To share hooks, point the core.hooksPath setting at a folder that is tracked in the repository.

Further reading: githooks documentation

More Commit tips git commit -C ORIG_HEAD git commit --fixup=reword:HEAD~1 git config --global commit.cleanup scissors git commit -m "Fix login redirect" -m "The old code sent signed-out users to a 404." Commit.template pre-fills your commit message All Commit tips (7) All topics

Link