Automatically Add Issue URL to Commit Message

I’ve spent too much time, twice, figuring this out, so I’m writing it here so future me won’t waste so much time. There are a lot of ways to do this, feel free to comment on your solution. I like my commit messages to contain the issue URL because 1) it tends to link the commit to the issue and vice versa in most git managers like github and gitlab 2) when searching git logs it makes it trivial to find the original issue.

We will be using a global gitmessage file and using a prepare-commit-msg hook. This assumes that your git branch will contain a group of digits which is the gitlab issue number. If your branch contains multiple groups of digits (jason/6456/description-stuff-343) then it assumes the first group of digits is the issue number

  1. Navigate to your project’s git hooks directory (ProjectDirectory/.git/hooks), and rename prepare-commit-msg.sample to prepare-commit-msg. By removing ‘sample’ you are telling git to actually use the file.

  2. Add this to your prepare-commit-msg. Note that this is for macOS, and if you’re using a different operating system your grep and sed commands might work differently.

# gets digits in current branch name. `head -1` gets just the first group. Note that this assumes you are adding your git issue numbers to your branches.

issueNumber=$(git symbolic-ref HEAD | grep -oE '\d+' | head -1)
# of course you need to change this URL to match your project's URL.
gitlabIssueURL="https:\/\/gitlab.com\/jasonmfry\/suchet-tts\/issues\/$issueNumber"

# if there's a digit in branch name
if [ -n "$issueNumber" ]; then
# replace #gitlabIssueURL with the value above
    sed -i '' -e "s/\#gitlabURL/$gitlabIssueURL/" "$1"

else
# delete the line containing #gitlabIssueURL
    sed -i '' -e "/\#gitlabURL/d" "$1"
fi
  1. Create a file (if you don’t have one already) named .gitmessage somewhere. Usually you should create it in your home directory, $HOME. Add #gitlabURL to wherever you want to add the url. Mine looks like this, to remind me how to make a decent commit message:
when applied, this commit will...

**Why:**

**How:**

Co-authored-by: username 

#gitlabURL
  1. Modify your global .gitconfig file, usually located in your home directory, $HOME, to add these two lines:
[commit]
    template = ~/.gitmessage

Putting all this together, whenever you do git commit, git runs the prepare-commit-msg hook, which will take your git message template (created in #3 above) and modify it with the fancy bash scripting we did in #2 above.

Leave a comment