Skip to content

Instantly share code, notes, and snippets.

@dogukancagatay
Last active July 16, 2024 10:59
Show Gist options
  • Save dogukancagatay/38792bf7ace99817555389e043ed954a to your computer and use it in GitHub Desktop.
Save dogukancagatay/38792bf7ace99817555389e043ed954a to your computer and use it in GitHub Desktop.
Git hook that prepends Jira issue ID from the branch name to the commit message
#!/usr/bin/env bash
#
# Git hook that appends Jira issue ID from the branch name to the commit message.
#
# e.g. for the branch name `feature/ABC-1234/add-xyz`, the `[ABC-1234]`
# is added to the commit message as well as summary.
#
# Installation:
# $ curl -fsSL -o .git/hooks/prepare-commit-msg \
# 'https://gist.githubusercontent.com/dogukancagatay/38792bf7ace99817555389e043ed954a/raw/prepare-commit-msg.sh'
#
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
# Extracts the issue key from the branch name
# e.g. feature/ABC-1234/add-xyz -> ABC-1234
JIRA_ISSUE_KEY="$(git symbolic-ref --short HEAD | awk -F/ '$2 ~ /[a-zA-Z]+-[0-9]+/ {print $2}')"
if [ "$SHA1" = "HEAD" ]; then
echo "Amending commit, skipping JIRA_ISSUE_KEY prepending"
exit 0
fi
# if it's a fixup! commit, don't add anything
if grep -q "fixup!" "$COMMIT_MSG_FILE"; then
echo "Fixup commit found, skipping JIRA_ISSUE_KEY prepending"
exit 0
fi
# if the message already has the JIRA_ISSUE_KEY prepended, don't change anything
if grep -q "\[$JIRA_ISSUE_KEY\]" "$COMMIT_MSG_FILE"; then
exit 0
fi
# write JIRA_ISSUE_KEY to commit message file
if [ -n "$JIRA_ISSUE_KEY" ]; then
sed -i.bak "1s;^;\[$JIRA_ISSUE_KEY\]\n\n\n\[$JIRA_ISSUE_KEY\];" "$COMMIT_MSG_FILE"
rm -rf "$COMMIT_MSG_FILE.bak"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment