Last active
April 16, 2021 05:06
-
-
Save markddavidoff/d9762718ff82c565df38d6deabbe6448 to your computer and use it in GitHub Desktop.
Git Commit Hook to add branch name to commit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# commit hook to prepend the JIRA ticket from the branch name to the commit | |
# Installation for one repo: | |
# - copy this file into your git repo's .git/hooks folder | |
# - make sure its executable: | |
# chmod a+x repo-path/.git/hooks/prepare-commit-msg | |
# Installation for all new repos: (you'll still have to do the above for already cloned repos) | |
# - tell git where your global hooks live: | |
# git config --global init.templatedir '~/.git-templates' | |
# - mkdir -p ~/.git-templates/hooks | |
# - copy this file to ~/.git-templates/hooks | |
# - make sure its executable: | |
# chmod a+x ~/.git-templates/hooks/prepare-commit-msg | |
# you can customize which branches should be skipped when | |
if [ -z "$BRANCHES_TO_SKIP" ]; then | |
BRANCHES_TO_SKIP=(master) | |
fi | |
BRANCH_NAME=$(git symbolic-ref --short HEAD) | |
BRANCH_NAME="${BRANCH_NAME##*/}" | |
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$") | |
TICKET_NUMBER_REGEX="[a-zA-Z][a-zA-Z2]*[-][0-9][0-9]*" | |
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && [[ $BRANCH_NAME =~ $TICKET_NUMBER_REGEX ]] | |
then | |
TICKET_NUMBER=$BASH_REMATCH | |
TICKET_IN_COMMIT=$(grep -c "$TICKET_NUMBER" $1) | |
if ! [[ $TICKET_IN_COMMIT -ge 1 ]] | |
then | |
printf "Prepending branch name to commit message...\n" | |
sed -i.bak -e "1s/^/$TICKET_NUMBER /" $1; | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment