Created
December 8, 2020 17:02
-
-
Save jlurena/03328deb8c7f666093698764a8d4f1f0 to your computer and use it in GitHub Desktop.
Prepend JIRA Card number in Git commit message
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
#!/bin/bash | |
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null) | |
PREFIX_PATTERN='[A-Za-z]{2,10}(-|_)[0-9]{1,6}' | |
# 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 ] && [[ $BRANCH_NAME =~ $PREFIX_PATTERN ]]; then | |
PREFIX=${BASH_REMATCH[0]} | |
PREFIX_FORMATTED=$(echo "${BASH_REMATCH[0]}" | tr '[:lower:]' '[:upper:]') | |
# Grab insensitive prefix in text at the beginning, if any. Ignore first and last character. | |
PREFIX_TEXT_IN_COMMIT=$(head -n 1 $1 | egrep -io -m 1 "^.?$PREFIX." | egrep -io "$PREFIX") | |
# If prefix is included in commit message ensure it is uppercased | |
# Enforce standard of [ABC-123] and add space if needed. | |
if [ ! -z "$PREFIX_TEXT_IN_COMMIT" ]; then | |
sed -i.bak "s/[^ A-Za-z0-9]*$PREFIX_TEXT_IN_COMMIT[^ A-Za-z0-9]*[ ]*/[$PREFIX_FORMATTED] /1" $1 | |
fi | |
# Ensure PREFIX exists in BRANCH_NAME and is not already present in the commit message | |
if [[ -n "$PREFIX" ]] && [ -z "$PREFIX_TEXT_IN_COMMIT" ]; then | |
sed -i.bak -e "1s~^~\[$PREFIX_FORMATTED\] ~" $1 | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
$1
is the path of the.git/COMMIT_EDITMSG
file in that repository.This handles the following cases (without caring for case sensitivity in branch) and
ABC-123
as well asABC_123