Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
prepare-commit-msg that gets JIRA ID from git branch name
#!/bin/sh
# Jira ID Extraction
# =================================
# Extract Jira ID from branch name and prepend to commit message.
#
# Takes a commit message like: "A commit comment" for branch "feature/SUM-1234-hello"
# and changes it to: "SUM-1234: A commit comment" for easier commit updates.
#
# Installation
# ============
# 1. Add this snippet to: `<REPO>/.git/hooks/prepare-commit-msg`
# 2. Make sure to `chmod a+x <REPO>/.git/hooks/prepare-commit-msg` to make the
# code actually executable.
#
# Define a Jira ID pattern.
JIRA_RE="[A-Z]+-[0-9]+"
echo "Prepending Jira ID"
BRANCH=$(git symbolic-ref --short HEAD)
echo "Branch: $BRANCH"
BRANCH_ID=($(echo "${BRANCH}" | egrep -o -m 1 "${JIRA_RE}"))
echo "Jira Id: ${BRANCH_ID[0]}"
# Check if the commit message **already** has a Jira ID.
EXISTING_ID=($(egrep -o -m 1 "${JIRA_RE}" $1))
if [ -n "$EXISTING_ID" ]; then
echo "Commit message already has a Jira Id: ${EXISTING_ID[0]}"
elif [ -n "$BRANCH_ID" ]; then
sed -i.bak -e "1s/^/${BRANCH_ID[0]}: /" $1
else
echo "Jira Id could not be determined."
fi
#!/bin/sh
# Jira ID Extraction
# =================================
# Extract Jira ID from branch name and prepend to commit message.
#
# Takes a commit message like: "A commit comment" for branch "feature/SUM-1234-hello"
# and changes it to: "SUM-1234: A commit comment" for easier commit updates.
#
# Installation
# ============
# 1. Add this snippet to: `<REPO>/.git/hooks/prepare-commit-msg`
# 2. Make sure to `chmod a+x <REPO>/.git/hooks/prepare-commit-msg` to make the
# code actually executable.
#
# Define a Jira ID pattern.
JIRA_RE="[A-Z]+-[0-9]+"
echo "Prepending Jira ID"
BRANCH=$(git symbolic-ref --short HEAD)
echo "Branch: $BRANCH"
BRANCH_ID="$(echo "${BRANCH}" | egrep -o -m 1 "${JIRA_RE}")"
echo "Jira Id: ${BRANCH_ID}"
# Check if the commit message **already** has a Jira ID.
EXISTING_ID="$(egrep -o -m 1 "${JIRA_RE}" $1)"
if [ -n "$EXISTING_ID" ]; then
echo "Commit message already has a Jira Id: ${EXISTING_ID}"
elif [ -n "$BRANCH_ID" ]; then
sed -i.bak -e "1s/^/${BRANCH_ID}: /" $1
else
echo "Jira Id could not be determined."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment