Add Github Issue Number to Git Commit Message

Add Github Issue Number to Git Commit Message

I have been working on a project with on Github and we are using Waffle.io to organize our issues on an agile board. One bad thing about Github is that it not always apparent what issue a commit resolved. To add context to commits I have begun appending the issue number to commit message. When viewing the commit in web interface of Github, it will automatically link to the issue. To accomplish this, I use commit that take the form of "This is my first commit [issue #123]". Obviously, this process can be automated.

First, I use branch names that start with the issue number. For example, the branch for issue 123 would be 123-new-user-form-fix and the branch for issue 345 would be 345-edit-user-form-fix.

Now with our naming convention in place, we can automatically append the issue number using a simple git hook. The following goes go in the file .git/hooks/commit-msg locally.

#!/bin/bash

# Extact issue number (e.g. 123-my-branch-name)
fetch_github_issue_no() {
  git rev-parse --abbrev-ref HEAD | grep -e '^[0-9]\+' -o
}

ISSUE_NO=`fetch_github_issue_no`
# Get the current commit message
MESSAGE="$(cat $1)"

# Append the issue number if the issue number is in the branch
# and the issue number is not already in the commit message.
if [ -n "$ISSUE_NO" ]  && [[ $MESSAGE != *"#$ISSUE_NO"* ]]
then
   NEW_MESSAGE="$MESSAGE [issue #$ISSUE_NO]"
   echo "New commit message: $NEW_MESSAGE"
   echo "$NEW_MESSAGE" > $1
fi