GIT hooks: commit-msg to enforce commit rules

Recently I forgot to add #reviewthis directive for modifications of codebase that belongs to team A. And a subtle bug was introduced that way. Ops! I agreed earlier that all changes done to moduleB should be passed to a reviewer that will do peer review for that particular change. What a shame 🙁 (We are using excellent GitHub's  review mechanism, BTW).

How to avoid that situation in a future? Should I rely on my memory? Is it possible for a human to track so many small rules manually? My intuition tells me that enforcement of those small ruleset should be automated.

GIT allows you to specify so called "commit hooks" that can validate many stages of GIT workflow. I'll use simplest local verification of commit message, first the rule in plain text:

If you are changing moduleB you should notify developerC about this change

The implementation (.git/hooks/commit-msg):

#!/bin/sh

if git st -s | grep -q moduleB; then
    grep -q '#reviewthis:.*developerC@xyz.com' $1 || {
        echo "Add #reviewthis.*developerC@xyz.com"
        echo "Commit aborted"
        false
    }
else
    true
fi

If you make a change in moduleB and developerC is not notified commit operation is aborted. You cannot forget (or else your commit will fail). If you want to make that rule repository-wide (in order to block everyone from skipping this rule) you should use different hook: pre-receive on a server.

GIT hooks are very powerful validation / automation mechanism that is making our work more efficient.

This entry was posted in en and tagged , , . Bookmark the permalink.