Git: How to automatically add the branch name to the end of every commit message

Today I learned… that git can be customized in a number of ways by using its hooks!

On my engineering team, it’s our convention to name feature branches after their corresponding JIRA issues. Likewise, we include the branch (issue) name in every commit message.

$ git commit -m "Fixed the thingy jira/story/ourproject-4555"

Including the branch name / issue name like this means the commit will show up in JIRA linked from the issue itself! Pretty cool. I’ve worked with JIRA a lot over the years, but I’ve never been on a team that actually integrates it with git like this, and the organizational benefits are worth the extra effort.

Alas, it is all too easy to forget to add the branch name at the end of a commit, and I got tired of amending my git messages (which is easy enough: git commit –amend will do it). I knew there had to be a way to automate this.

Adding a git hook

  1. Go into your project’s repo
  2. Open ./git/hooks directory (remember, .git is a hidden directory by default)
  3. Make a copy of .git/hooks/prepare-commit-msg.sample, paste it into the same folder, and remove the .sample extension. You should have a file named simply prepare-commit-msg with no extension.
  4. Paste this into the new file:
# Automatically adds branch name to the end of every commit message.

NAME=$(git branch | grep '*' | sed 's/* //')
echo $(cat "$1") "$NAME" > "$1"

The first line gets the git branch name and sets it to “NAME”.

The second line echoes the contents of your commit message (represented as $1), adds “NAME” to it, and replaces $1 with your message + NAME.

Just save the file and try it out in bash now! No need to reload bash or source anything.

Gist:

More examples

There are many ways to approach this problem, and you can do a lot of sophisticated things with Git hooks. Here are some resources I found helpful in learning about git hooks and git in general:

 

One thought on “Git: How to automatically add the branch name to the end of every commit message”

  1. Including the branch name / issue name like this means the commit will show up in JIRA linked from the issue itself! Pretty cool. I’ve worked with JIRA a lot over the years, but I’ve never been on a team that actually integrates it with git like this, and the organizational benefits are worth the extra effort.home fixer

Leave a Reply

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