Skip to content

Instantly share code, notes, and snippets.

@andrewandante
Created November 20, 2019 14:54
Show Gist options
  • Save andrewandante/8f734a6ddb586860cfe9e701eece0dc5 to your computer and use it in GitHub Desktop.
Save andrewandante/8f734a6ddb586860cfe9e701eece0dc5 to your computer and use it in GitHub Desktop.
Git hook to prefix commit with beginning of branch name
#!/bin/bash
# To use - go into your root directory, and rename the file .git/hooks/prepare-commit-msg.sample to .git/hooks/prepare-commit-msg
# Then, copy this into that file. Make it executable (chmod +x .git/hooks/prepare-commit-msg) and then reload your terminal
# This will then prepend the start of the branch name to your commit messages e.g. [ABC-1234] My sick commit message
# This way you can customize which branches should be skipped when
# prepending commit message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master)
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_CODE=$(echo "$BRANCH_NAME" | egrep -o '[A-Z]{2}-[0-9]+' | head -n1)
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_CODE\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/[$BRANCH_CODE] /" $1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment