Enhancing your git commit editor

Note, this article was published over 3 years ago and hence the content may be stale. Consume with a pinch of salt.

Confession: I am a pedant, especially around commit messages.

I often find myself writing very similar commit messages (like "Bump version to 0.4.3") and want to ensure I use the same wording each time. Thanks to @LuRsT, I learnt how to employ git's prepare-commit-msg hook to display the last 5 commit messages when I'm editing a commit message.

Use the following .git/hooks/prepare-commit-msg hook:

#!/bin/sh

BRANCH_NAME=$(git branch | grep '*' | sed 's/* //')
if [ $BRANCH_NAME != '(no branch)' ]
then
    echo "#" >> $1
    echo "# Last 5 commit messages" >> $1
    echo "# ----------------------" >> $1
    COMMITS=`git log --pretty=format:"# %h %s [%an]" -5`
    echo "${COMMITS}" >> $1
fi

then your default commit template looks like this:

/static/images/screenshots/git-commit-editor.png

Note, using echo "${COMMITS}" (instead of echo $COMMITS) ensures newlines are preserved (which I learnt in this Stack Overflow answer). Also we don't echo commit messages while rebasing as it has strange side-effects.