Last active
October 12, 2023 16:58
-
-
Save phillpafford/02437d61a90a8d5f8cd520944a7b618c to your computer and use it in GitHub Desktop.
add jira ticket from git branch as prepare-commit-msg git hook
This file contains hidden or 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
#!/usr/bin/env bash | |
## Automatically append jira issue ticket to every commit if found in the git branch name and not already in the commit message | |
## Ref: https://community.atlassian.com/t5/Bitbucket-questions/automatically-append-JIRA-issue-ID-into-commit-message/qaq-p/605991 | |
## https://stackoverflow.com/a/67647814/93966 | |
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null) | |
# It will copy the commit string from ".git/COMMIT_EDITMSG" | |
COMMIT_MESSAGE=$1 | |
COMMIT_MESSAGE=`head -n1 $COMMIT_MESSAGE` | |
# Ensure BRANCH_NAME is not empty and is not in a detached HEAD state (i.e. rebase). | |
# SKIP_PREPARE_COMMIT_MSG may be used as an escape hatch to disable this hook, | |
# while still allowing other githooks to run. | |
if [ ! -z "$BRANCH_NAME" ] && [ "$BRANCH_NAME" != "HEAD" ] && [ "$SKIP_PREPARE_COMMIT_MSG" != 1 ]; then | |
PREFIX_PATTERN='[A-Z0-9]{2,10}-[0-9]{1,7}' | |
[[ $BRANCH_NAME =~ $PREFIX_PATTERN ]] | |
PREFIX=${BASH_REMATCH[0]} | |
PREFIX_IN_COMMIT=$(echo $COMMIT_MESSAGE | grep -c "$PREFIX") | |
# echo "COMMIT_MESSAGE: $COMMIT_MESSAGE" | |
# echo "PREFIX: $PREFIX" | |
# echo "PREFIX_IN_COMMIT: $PREFIX_IN_COMMIT" | |
# Ensure PREFIX exists in BRANCH_NAME and is not already present in the commit message | |
if [[ -n "$PREFIX" ]] && ! [[ $PREFIX_IN_COMMIT -ge 1 ]]; then | |
sed -i '' -e "1s/$/\n\n\[$PREFIX\]/" $1 | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment