Skip to content

Instantly share code, notes, and snippets.

@huskercane
Created October 24, 2023 19:36
Show Gist options
  • Save huskercane/d9f08209c8d6f569ba781099d3c1de62 to your computer and use it in GitHub Desktop.
Save huskercane/d9f08209c8d6f569ba781099d3c1de62 to your computer and use it in GitHub Desktop.
Add jira id to commit message
#!/bin/sh
#
# 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.
#
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
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
# Use sed to extract "SPAOP-1363"
parsed_string=$(echo "$BRANCH_NAME" | sed 's/.*\///')
# Use awk to further refine the result
PREFIX_IN_COMMIT=$(echo "$parsed_string" | awk -F '-' '{print $1 "-" $2}')
# 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 #suffix
# sed -i.bak -e "1s~^~[$PREFIX] ~" $1 #prefix
fi
echo "$PREFIX_IN_COMMIT" >> "$COMMIT_MSG_FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment