I read this post and realised I had been writing unhelpfully terse commit messages for many years. I went down a rabbit hole and discovered you can have a template commit message which you manually customise for each commit. I got some tips on configuring vim from this article. Then I wondered if it was possible to populate the template dynamically. I found this answer but didn’t have time to get my head around the vim scripting, so I decided to do it myself in bash.

Requirements

  • Template file for git commit messages
  • Auto-filled with Jira issue number, scraped from the branch name
  • Automatically word-wrapped and spell-checked by my text editor
  • Available from both zsh and bash

Files

~/.git-commit-template.orig

ISSUE Title

Body

~/.vimrc

filetype on
colorscheme industry
autocmd FileType gitcommit set textwidth=72 colorcolumn=+1 colorcolumn+=51 spell

~/.bash_profile

source ~/.zshrc

~/.zshrc

export EDITOR=/usr/bin/vim

alias gc='ISSUE=$(git branch --show-current | grep -oE "DF-[0-9]+"); sed "s,ISSUE,$ISSUE,g" ~/.git-commit-template.orig > ~/.git-commit-template; git commit'

Configuration

I ran the following commands.

# Setup git to use template
cp ~/.git-commit-template.orig ~/.git-commit-template
git config --global commit.template ~/.git-commit-template

# Make the original read-only
chmod 0440 ~/.git-commit-template.orig

Usage

To commit, I type gc and vim opens with the pre-filled template. On saving and quitting vim, the commit is made.


How it works

The gc alias gets the current branch with

git branch --show-current

and extracts the Jira issue number using the regular expression "DF-[0-9]+". The letters at the start are the Jira project code. If you have more than one Jira project, you probably have to make a different alias for each one.

It then reads the original read-only template file, replaces the word ISSUE with the issue number, and writes the output to the actual file that git uses for the commit template. Finally, it starts a new commit.

Because it is an alias, you can append any additional arguments you need to supply to the git commit command. For example, gc --amend will run git commit amend at the end of the command.

Update April 2023

Git has a built-in feature which enables this functionality – see the prepare-commit-msg hook. The approach I used above is still useful in cases where hooks are being managed team-wide by the repository owner.

Leave a Reply

Your email address will not be published. Required fields are marked *