mherod
9/19/2017 - 1:09 PM

prepare-commit-msg

#!/bin/sh

# If commit message does not refer to any JIRA issue number,
# this hook will parse the JIRA issue from the current branch and 
# prepend it to the commit message.
# It will also ignore any brnahces that have no valid JIRA issue number
# 
# Example:
# Branch: GW-645 or GW-645-some-text
# commit message: Updated README.md 
# prepended commit message: CW-645 Updated README.md
#
# Example:
# Branch: wwww-seo
# commit message: Updated README.md 
# prepended commit message: Updated README.md
#
# Install
# Copy this file into your projects .git/hooks/prepare-commit-msg file
#

parse_issue () {
    local match
    local re="\([a-zA-Z][a-zA-Z]-[0-9][0-9]*\)"
    match=$(echo $1 | sed -n "s/.*$re.*/\1/p")
    [ -z "$match" ]  && match=$(echo $1 | sed -n "s/^$re/\1/p")
    match=$(echo $match | tr [a-z] [A-Z])
    echo $match
}

source=$2
commit_msg=$(cat $1)
branch=$(git symbolic-ref --short HEAD)

commit_issue=$(parse_issue "$commit_msg")
branch_issue=$(parse_issue "$branch")

if [ "$source" = "message" -a -n "$branch_issue" -a -z "$commit_issue" ] 
then
    new_commit_msg="[${branch_issue}] $commit_msg"
    echo $new_commit_msg > $1
fi