Skip to content

Instantly share code, notes, and snippets.

@brianmock
Last active February 16, 2022 18:37
Show Gist options
  • Save brianmock/98a04e4293867e7635e54258ed2017ae to your computer and use it in GitHub Desktop.
Save brianmock/98a04e4293867e7635e54258ed2017ae to your computer and use it in GitHub Desktop.
prepare-commit-msg git hook
#!/bin/bash
# Add this snippet to repo/.git/hooks/prepare-commit-msg
#
# Credit: https://medium.com/bytelimes/automate-issue-numbers-in-git-commit-messages-2790ae6fe071
#
# Inspects branch name and checks if it contains a Jira ticket number (i.e. ABC-123).
# If yes, commit message will be automatically prepended with [ABC-123].
#
# Useful for looking through git history and relating a commit or group of commits
# back to a user story.
#
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
# 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-Z]{2,5}-[0-9]{1,4}'
[[ $BRANCH_NAME =~ $PREFIX_PATTERN ]]
PREFIX=${BASH_REMATCH[0]}
PREFIX_IN_COMMIT=$(grep -c "\[$PREFIX\]" $1)
# 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.bak -e "1s~^~[$PREFIX] ~" $1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment