Skip to content

Instantly share code, notes, and snippets.

@stoerr
Created April 12, 2019 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stoerr/8ebcbb1692b81a54d9a9cb843c30c48e to your computer and use it in GitHub Desktop.
Save stoerr/8ebcbb1692b81a54d9a9cb843c30c48e to your computer and use it in GitHub Desktop.
Automatically include ticket number from branch name into git commit messages
#!/bin/bash
# If you use branch names with JIRA ticket numbers in them, e.g. feature/ABC-4324-do-something,
# this includes automatically the ticket number (ABC-4324) at the start of the the commit message.
# This way, it's later easy to see which change was done for which ticket, without any manual effort.
# You need to copy or link this file into .git/hooks/prepare-commit-msg
# You can customize which branches should be skipped when prepending commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop test)
fi
BRANCH_NAME=`git symbolic-ref --short HEAD`
if [[ $BRANCH_NAME =~ /([A-Z]{1,4}-[0-9]{1,4}) ]]; then
TICKET_NAME=${BASH_REMATCH[1]}
fi
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(fgrep -c -w "$TICKET_NAME" $1)
if [ -n "TICKET_NAME" ] && ! [[ $BRANCH_EXCLUDED -ge 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^\s*/$TICKET_NAME /" $1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment