Last active
October 4, 2024 14:07
-
-
Save georgescumihai/c368e199a9455807b9fbd66f44160095 to your computer and use it in GitHub Desktop.
Git pre commit hook to add the jira ticket id to the commit message
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
#!/bin/sh | |
# | |
# A hook script to prepare the commit log message. | |
# If the branch name it's a jira Ticket. | |
# It adds the branch name to the commit message, if it is not already part of it. | |
# https://stackoverflow.com/questions/5894946/how-to-add-gits-branch-name-to-the-commit-message/59831864#59831864 | |
branchPath=$(git symbolic-ref -q HEAD) #Somthing like refs/heads/myBranchName | |
branchName=${branchPath##*/} #Get text behind the last / of the branch path | |
regex="(PROJECTNAME-[0-9]*)" | |
# Enable case insensitive match, jira project codes are uppercase | |
shopt -s nocasematch | |
if [[ $branchName =~ $regex ]] | |
then | |
# Get the captured portion of the branch name, and change it to upper case. | |
# Mac bash version is 3, so can't use the `^^` to uppercase the string, using `tr` command instead. | |
# If you do not need the uppercase, use the BASH_REMATCH dirrectly | |
# jiraTicketName${BASH_REMATCH[1]} | |
jiraTicketName=$(echo ${BASH_REMATCH[1]} | tr [:lower:] [:upper:]) | |
originalMessage=`cat $1` | |
# If the message already begins with PROJECTNAME-#, do not edit the commit message. | |
if [[ $originalMessage == $jiraTicketName* ]] | |
then | |
exit | |
fi | |
sed -i '.bak' "1s/^/$jiraTicketName: /" $1 #Insert branch name at the start of the commit message file | |
fi | |
# else => do not edit the commit message. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment