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 <[email protected]>
Date: Thu Jul 15 12:26:17 2021 +0300
[TEST-123] fix: No more YOLO! in commit, Sang.
Enjoy!