Skip to content

Instantly share code, notes, and snippets.

@iMartyn
Last active January 20, 2021 14:01
Show Gist options
  • Save iMartyn/0229c82ff362d0c13c4a625814093695 to your computer and use it in GitHub Desktop.
Save iMartyn/0229c82ff362d0c13c4a625814093695 to your computer and use it in GitHub Desktop.
Add Jira ref to commit messages
#!/bin/sh
# Uncomment below if you want the commit messages to start [refs: jira-123] or you'll just get [jira-123]
#PREAMBLE="refs: "
SED=sed
# If you're on mac and you don't have gnu sed installed, heaven help you.
if uname | grep "Darwin" 2>&1 > /dev/null; then
SED=gsed
fi
if ! which $SED | grep sed > /dev/null 2>&1; then
echo "It looks like you don't have gnu sed and you're on OS/X, install it with"
echo " brew install gnu-sed "
echo "For other scripts that use sed, you might want to default to it with"
echo " ln -s /usr/local/bin/gsed /usr/local/bin/sed"
echo "after it's installed"
exit 0
fi
BRANCH=$(git symbolic-ref HEAD)
ORIGCOMMITMSG=$(cat $1)
BRANCH_SANS_HEADS_FEATURES_ETC=$(echo $BRANCH | $SED -e 's/^refs\/heads\/\([a-z]*\/\)\?//gm')
JIRAREF=$(echo $BRANCH_SANS_HEADS_FEATURES_ETC | $SED -r -e 's/^([A-Za-z]+-[0-9]+)?(.*)/\1/gm')
echo -n "Maybe ticket is "
echo $JIRAREF
echo "Orig commit message : ${ORIGCOMMITMSG}"
if echo $ORIGCOMMITMSG | grep '^\[' > /dev/null 2>&1; then
echo "Commit message already starts with squarebracket, making no changes."
NEWCOMMITMSG=$ORIGCOMMITMSG
exit 0
fi
if [ "$JIRAREF" = "" ]; then
echo "Couldn't work out branch... not messing with commit message"
NEWCOMMITMSG=$ORIGCOMMITMSG
exit 0
fi
NEWCOMMITMSG="[${PREAMBLE}${JIRAREF}] $ORIGCOMMITMSG"
echo "New commit message : ${NEWCOMMITMSG}"
echo -n "${NEWCOMMITMSG}" > $1
@iMartyn
Copy link
Author

iMartyn commented Apr 4, 2017

Place this file in ~/.git/hooks/commit-msg and set your core.hookspath to $HOMEDIR/.git/hooks
git config --global core.hooksPath $HOME/.git/hooks
Requires 1.9 or higher of git.

@iMartyn
Copy link
Author

iMartyn commented Apr 4, 2017

It pulls the jira ref from the branch name in gitflow branchnames or any branchname that starts with a jira ref so copes with branches such as ABC-123-a-big-issue or bugfix/DEF-22 etc.
It results in commit messages like :
[GHI-987] Original commit message here
and doesn't touch messages that already have something in square brackets at the start of the message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment