Skip to content

Instantly share code, notes, and snippets.

@sangdth
Last active July 15, 2021 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangdth/6c1184b809ec621cb65bd57575987364 to your computer and use it in GitHub Desktop.
Save sangdth/6c1184b809ec621cb65bd57575987364 to your computer and use it in GitHub Desktop.
Automatically prepend git commit with JIRA code from branch name

In my company we use Jira, and our branch's name follows this convention CODE-123-Something-descriptive-after And I want to have that code automatically whenever I commit with message. So, you can exclude the grep part if you want to get the whole branch name

Copy the script below, name it prepare-commit-msg and put it under git/hooks folder. Make sure you make it executable by chmod 755 your/path/prepare-commit-msg

#!/bin/bash

if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master main develop dev test hotfix stage)
fi

BRANCH_NAME=$(git symbolic-ref --short HEAD | grep -oE "([a-zA-Z]+)-(\d+)" | awk '{print $1}')
BRANCH_NAME="${BRANCH_NAME##*/}"

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
fi

Now whenever I commit, I will have this format in git log:

commit 586f72e2a3d63bbc092f8a7bd070e83997b1717c (HEAD -> TEST-123-something-super-long-here)

Author: Sang Dang <sangdth@gmail.com>
Date:   Thu Jul 15 12:26:17 2021 +0300

    [TEST-123] fix: No more YOLO! in commit, Sang.

Enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment