DEV Community

Irtiza Ali
Irtiza Ali

Posted on

Add Git branch name to each commit

git hook image


This story is about how to utilize git hooks in order to add branch name to each commit. I have used the script from this article and modified it to my needs to minimize the restrictions.


Follow the instruction given below to enable it:

  • Move inside your repository's home directory.

  • Rename the .git/hooks/prepare-commit-msg.example to .git/hooks/prepare-commit-msg

  • Change file permissions:

sudo chmod 755 .git/hooks/prepare-commit-msg
Enter fullscreen mode Exit fullscreen mode
  • Paste the script given below in that file
# Automatically adds branch name and branch description to every commit message.
# Modified from the gist here

# This way you can customize which branches should be skipped when
# prepending commit message.

if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master production staging main)

AUTHORINFO=$(git var GIT_AUTHOR_IDENT) || exit 1
NAME=$(printf '%s\n\n' "${AUTHORINFO}" | sed -n 's/^\(.*\) <.*$/\1/p')
# Regex to check the valid branch name

# Get branch name and description
BRANCH_NAME=$(git branch | grep '*' | sed 's/* //')

# Branch name should be excluded from the prepend
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")

# A developer has already prepended the commit in the format BRANCH_NAME

# check the branch name is valid or not
if [[ "$BRANCH_NAME" =~ $VALID_BRANCH_REGEX ]]; then
  # if face any error in mac then run chmod u+x .git/hooks/prepare-commit-msg and restart your terminal
  if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then 
    sed -i.bak -e "1s/^/[$BRANCH_NAME] /" $1
  echo -e "\n${RED}Please correct the branch name${NOCOLOR}"
  printf "\nBranch Name not as per the defined rules like:  "
  echo -e "${GREEN}dev, hotfix, bugfix, release, dev, improvement, hotfix-102\n"
  echo -e "${ORANGE}You cannot push in these branches directly: ${BRANCHES_TO_SKIP[@]}\n"
  echo -e "${ORANGE}Current BRANCH_NAME: ${BRANCH_NAME}"
  echo -e "\n${RED}Oh, please stop. I cannot allow you to commit with your current branch: ${BRANCH_NAME}${NOCOLOR}"
  exit 1;
Enter fullscreen mode Exit fullscreen mode
  • After these changes, the branch name will be added to your every commit and it will look like this

commit message

  • It will not allow you to commit directly to the following branch
  1. master
  2. production
  3. staging
  4. main
  • You can change these restrictions based on your requirements.

Final Thoughts

I hope you would love this story and let me know if anything can be improved.

thank you

Discussion (0)