Skip to content

Instantly share code, notes, and snippets.

@jlurena
Created December 8, 2020 17:02
Show Gist options
  • Save jlurena/03328deb8c7f666093698764a8d4f1f0 to your computer and use it in GitHub Desktop.
Save jlurena/03328deb8c7f666093698764a8d4f1f0 to your computer and use it in GitHub Desktop.
Prepend JIRA Card number in Git commit message
#!/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
@jlurena
Copy link
Author

jlurena commented Dec 8, 2020

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 as ABC_123

BRANCH name CommitMessage Result
hello_there_you Did a thing Did a thing
ABC-123 Did a thing [ABC-123] Did a thing
ABC-123 [ABC-123] Did a thing [ABC-123] Did a thing
ABC-123 {ABC-123} Did a thing [ABC-123] Did a thing
ABC-123 ABC-123: Did a thing [ABC-123] Did a thing
ABC-123 {ABC-123:} Did a thing [ABC-123] Did a thing
ABC-123 [ABC-123](lots of spaces) Did a thing [ABC-123] Did a thing
ABC-123 [ABC-123] Did a thing relevant to ABC-5432 [ABC-123] Did a thing relevant to ABC-5432
ABC-123-hot-fix Hot fix [ABC-123] Hotfix
ABC-123-hot-fix ABC-123: Hot fix [ABC-123] Hotfix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment