Skip to content

Instantly share code, notes, and snippets.

@nicolopignatelli
Last active August 21, 2020 09:44
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 nicolopignatelli/d9ee53886476c091568297ba59c4f33e to your computer and use it in GitHub Desktop.
Save nicolopignatelli/d9ee53886476c091568297ba59c4f33e to your computer and use it in GitHub Desktop.
Git hooks enforcing branch name and commit message to include a formally valid JIRA issue key.
#!/bin/sh
# This hook enforces the following commit message format "[PROJ-123] some message"
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
INPUT_FILE=$1
MATCHED_MERGE_COMMIT=`head -n1 $INPUT_FILE | grep -E "\W*(Merge remote-tracking branch \'origin\/master\')\W*" | wc -c`
MATCHED_MSG_LENGTH=`head -n1 $INPUT_FILE | grep -E '^\b\[[A-Z]{2,5}-[[:digit:]]+\] [a-zA-Z]{1,80}' | wc -c`
if [ ${MATCHED_MSG_LENGTH} -eq 0 ] && [ ${MATCHED_MERGE_COMMIT} -eq 0 ] ; then
echo "---------------------------------------------------------------------------"
echo "* ${RED}Bad commit message, Please use a valid Project Key from Jira ${NC}"
echo "* Valid Example: ${CYAN}[PROJ-123] some message ${NC}"
echo "---------------------------------------------------------------------------"
exit 1
fi
#!/bin/sh
# This hook enforces the following branch name prefix "PROJ-123"
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BRANCH_NAME_LENGTH=`git rev-parse --abbrev-ref HEAD | grep -E '^\b[A-Z]{2,5}-[[:digit:]]+-' | wc -c`
if [ ${BRANCH_NAME_LENGTH} -eq 0 ] ; then
echo "-------------------------------------------------------------------------------"
echo "* ${RED}Invalid Branch Name!${NC}"
echo "* Valid format: ${CYAN}PROJ-123-your-branch-name-description${NC}"
echo "-------------------------------------------------------------------------------"
exit 1
fi
#!/bin/sh
# This hook extracts the JIRA issue key from the branch name and automatically prepends it to the commit message.
BRANCH_NAME=$(git branch 2>/dev/null | grep -e ^* | tr -d ' *')
if [ -n "$BRANCH_NAME" ] && [ "$BRANCH_NAME" != "master" ] && [ "$BRANCH_NAME" != "(nobranch)" ]; then
IFS='-'
read -ra DETAILS <<< "$BRANCH_NAME"
echo "[${DETAILS[0]}-${DETAILS[1]}] $(cat $1)" > $1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment