Skip to content

Instantly share code, notes, and snippets.

@ThatRubenAguilar
Last active March 13, 2017 20:03
Show Gist options
  • Save ThatRubenAguilar/1f5c8c2e4aad243eef42f9d95e520929 to your computer and use it in GitHub Desktop.
Save ThatRubenAguilar/1f5c8c2e4aad243eef42f9d95e520929 to your computer and use it in GitHub Desktop.
How to automatically prepend git commit with a branch name except for major branches
#!/bin/sh
#
# Prepend the branch name to the commit message
# Based on https://gist.github.com/bartoszmajsak/1396344
#
# Add this file as [repo]/.git/hooks/prepare-commit-msg
#
# A couple notes:
# 1. The file must be executable (chmod +x prepare-commit-msg)
# 2. This works on a per-repo basis (unless you follow this guide https://coderwall.com/p/jp7d5q/create-a-global-git-commit-hook)
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop test prerelease stage integration production)
fi
if [ -z "$BRANCHES_INCLUDE_REGEX" ]; then
BRANCHES_INCLUDE_REGEX=[-]
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_INCLUDED=$(printf "%s\n" "$BRANCH_NAME" | grep -c -E "$BRANCHES_INCLUDE_REGEX")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && [[ BRANCH_INCLUDED -ge 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/[$BRANCH_NAME] /" $1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment