Adding Branch Name In The Commit Message Automatically Using Git Hooks

Github Hooks is an amazing tool to automate actions before or after executing a git command. Some common scenarios where we can use hooks are,

  • Validate the format (using eslint for example) before a commit
  • Validate the commit message format
  • Update a version of a file or settings
  • Add a default text in the commit message

In this article, we will learn how to add as a default text the branch name in the commit message. A common practice is to create a new branch for each new story putting as name the ticket or story number, in this way, we can perform some other action like move the ticket automatically to doing status when the branch is created or create a link between the user story and each commit in the branch.

Some examples of user story numbers in Jira or other bug trackers are,

  • U-0001
  • COMP-0001
  • STORY-001

To create our hook for adding the branch name in the commit message we need to navigate to the hooks' folder in our projects.

Navigate to your folder's project and open .git folder and then hooks folder. There you will find some default templates to create your own hook. 

Example on macOS,

Adding Branch Name In The Commit Message Automatically Using Git Hooks

Now you have to create a file with the name prepare-commit-msg. Prepare commit message is the action executed before setting the message in the commit. 

Within prepare-commit-msg file you need to add the following code,

# prepending commit message. 
if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master develop release)

BRANCH_NAME=$(git symbolic-ref --short HEAD)

BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)

if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then 
  sed -i.bak -e "1s/^/$BRANCH_NAME - /" $1

In line number 13, you can see how the branch name is set. You can add more default text or words after the branch name. In this case, we only have a dash.

Using this configuration you only need to add your message and by default it will add the branch name at the beginning of the commit message. 

Similar Articles