Skip to content

Instantly share code, notes, and snippets.

@xavarius
Forked from bartoszmajsak/prepare-commit-msg.sh
Last active December 18, 2019 10:23
Show Gist options
  • Save xavarius/c2f7a89886d8927a49d8fcaba612ac68 to your computer and use it in GitHub Desktop.
Save xavarius/c2f7a89886d8927a49d8fcaba612ac68 to your computer and use it in GitHub Desktop.
How to automatically prepend git commit with a branch name
#!/bin/bash
# Script provides effortless way of prepending Jira ticket number
# into a commit message.
# It is compatible with "git flow" naming approach for branches :: f.ex feature/AVENGERS-667.
# Installation
# Put this file into rootProject/.git/hooks dir.
# Make it executable. (with chmod)
COMMIT_MSG=$(<$1)
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME_PATTERN="(([A-Z]+|[a-z]+)-[0-9]+)"
BRANCHES_TO_SKIP=(master develop test)
SPLITTED=(${BRANCH_NAME//// })
BRANCH_TYPE=${SPLITTED[0]}
TICKET_NAME=${SPLITTED[1]}
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_TYPE$")
if [ -n "$TICKET_NAME" ] && ! [[ ${BRANCH_EXCLUDED} -eq 1 ]] && ! [[ ${COMMIT_MSG} =~ $BRANCH_NAME_PATTERN ]] && [[ $2 != "" ]] ; then
if [[ ${TICKET_NAME} =~ ${BRANCH_NAME_PATTERN} ]]; then
TICKET_NAME=${BASH_REMATCH[1]}
fi
sed -i.bak -e "1s/^/$TICKET_NAME: /" $1
fi
@xavarius
Copy link
Author

xavarius commented Feb 20, 2018

Installation notes

  1. Within repo root execute: cd .git/hooks/
  2. Copy this file as a prepare-commit-msg into */hooks/ dir
  3. Make it executable. F.ex with chmod 755 prepare-commit-msg
  4. Return to root. Commit. Review commit message to see magic happened.

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