Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically prepend JIRA issue key to commit message
#!/bin/sh
#
# Automatically adds Jira key to commit message
#
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_JIRA_KEY=$(echo $BRANCH_NAME | grep -E -o '^([A-Z]+-[0-9]+)')
if ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $(cat "$1") == "$BRANCH_JIRA_KEY"* ]] && ! [ -z "$BRANCH_JIRA_KEY" ]; then
echo "$BRANCH_JIRA_KEY $(cat "${1}")" > "$1"
fi
@wingleung

This comment has been minimized.

Copy link
Owner Author

commented Dec 12, 2014

Automatically add JIRA issue key from branch name to commit message.

It will:
... get the JIRA issue key of the branch
... only prepend the JIRA key if branch name is not blacklisted AND jira issue key isn't already in the commit message

Install

In your git repository go to .git/hooks/
Make a copy of prepare-commit-msg.sample and rename it to prepare-commit-msg
Paste in the code

Credit

Credits go to @bartoszmajsak for the script this is based on.
https://gist.github.com/bartoszmajsak/1396344

@wingleung

This comment has been minimized.

Copy link
Owner Author

commented Dec 13, 2014

Updated to support branches from git flow (eg. feature/JIRA-0000-Branch-name)

@wingleung

This comment has been minimized.

Copy link
Owner Author

commented Dec 13, 2014

Updated to use a regex to get the jira issue key.
Jira keys are selected by the following regex ^([A-Z]+-[0-9]+)

  • Begins with 1 or more uppercase letters
  • followed by a hyphen '-'
  • followed by 1 or more numbers
@v-sh

This comment has been minimized.

Copy link

commented Nov 30, 2017

This script ingnores newlines and merges averything in one line if you don't use git commit -m, we changed to this line:

echo -e "[$BRANCH_JIRA_KEY] $(cat "${1}")" > "$1"
@wingleung

This comment has been minimized.

Copy link
Owner Author

commented Jul 27, 2018

Thank you! I've updated the code with your snippet

edit echo -e doesn't work on my mac, it's only for linux as far as I know

@mcascone

This comment has been minimized.

Copy link

commented May 20, 2019

this is fantastic, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.