Skip to content

Instantly share code, notes, and snippets.

@Lowess
Forked from bartoszmajsak/prepare-commit-msg.sh
Last active March 4, 2020 10:50
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 Lowess/ccb73bba54be6951b22195b94f1d61d8 to your computer and use it in GitHub Desktop.
Save Lowess/ccb73bba54be6951b22195b94f1d61d8 to your computer and use it in GitHub Desktop.
How to automatically prepend git commit with a branch name
(MLE-297-Fix-naming-for-prometheus) $ ./prepare-commit-msg.sh 'Fix featureA in controller'
[MLE-297] Fix featureA in controller
#!/bin/bash
# This way you can customize which branches should be skipped when
# prepending commit message.
if [ -z "${BRANCHES_TO_SKIP}" ]; then
BRANCHES_TO_SKIP=(master develop stage test)
fi
if [ -z "${ENFORCE_JIRA_PATTERN}" ]; then
ENFORCE_JIRA_PATTERN=0
fi
# Grab the current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
# Strip any Gitflow prefix like hotfix/ bugfix/ feature/
BRANCH_NAME="${BRANCH_NAME##*/}"
# Attempt to detect Jira project and ticket number format from the branch name
BRANCH_PROJECT="${BRANCH_NAME%%-*}"
_BRANCH_REMAINING="${BRANCH_NAME##"${BRANCH_PROJECT}-"}"
BRANCH_TICKET="${_BRANCH_REMAINING%%-*}"
JIRA_PREFIX="${BRANCH_PROJECT}-${BRANCH_TICKET}"
JIRA_PROJECT_REGEX='^[A-Z]{2,10}-[0-9]{1,5}$'
# Check if the branch is part of excluded ones
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -s -c "^$BRANCH_NAME$")
# Check if the branch name is already in commit
BRANCH_IN_COMMIT=$(echo "${1}" | grep -c "\\[${BRANCH_NAME}\\]")
JIRA_IN_COMMIT=$(echo "${1}" | grep -c "\\[${JIRA_PREFIX}\\]")
if [ -n "${BRANCH_NAME}" ] \
&& ! [[ ${BRANCH_EXCLUDED} -eq 1 ]] \
&& ! [[ ${BRANCH_IN_COMMIT} -ge 1 ]] \
&& ! [[ ${JIRA_IN_COMMIT} -ge 1 ]]; then
if [[ "${BRANCH_PROJECT}-${BRANCH_TICKET}" =~ ${JIRA_PROJECT_REGEX} ]] ; then
echo "${1}" | sed -e "s/^/[${JIRA_PREFIX}] /"
else
# When JIRA pattern is enforced fail pre-commit on purpose
if [[ ${ENFORCE_JIRA_PATTERN} -eq 1 ]]; then
exit 1
else
echo "${1}" | sed -e "s/^/[${BRANCH_NAME}] /"
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment