Skip to content

Instantly share code, notes, and snippets.

@windgazer
Forked from bartoszmajsak/prepare-commit-msg.sh
Last active January 8, 2019 14:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save windgazer/a3a2120eeb8e4f8d75e2 to your computer and use it in GitHub Desktop.
Save windgazer/a3a2120eeb8e4f8d75e2 to your computer and use it in GitHub Desktop.
How to automatically prepend git commit with a branch name. TLDR, from the root of each repository you want to use this, install using `curl -L https://goo.gl/5Mmuoi -o .git/hooks/prepare-commit-msg --create-dirs; chmod 744 .git/hooks/prepare-commit-msg`
#!/bin/bash
# To update or install in a new repository, run the following command
# N=.git/hooks/prepare-commit-msg ; curl -L https://goo.gl/5Mmuoi -o $N --create-dirs; chmod 744 $N
# Assuming all branches are created as `WWW-nnn-Human-readable-suffixes`
# this commit-msg hook will prepend all commit messages with the ticket
# name/number, for example:
# Branch: ADV-007-License-to-kill
# Message: Bad guy has been identified.
# Prepends: ADV-007:
# Result: ADV-007: Bad guy has been identified.
# This way you can customize which branches should be skipped when
# prepending commit message. (Untested after implementing trimming)
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop test)
fi
# Get the full branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
# Chop of sub-dirs (like `feature/`)
BRANCH_NAME="${BRANCH_NAME##*/}"
# Keep only ticket-number, ditch the human readable part i.e. `ADV-000`
BRANCH_NAME=$(echo $BRANCH_NAME | sed -e 's:^\([^-]*-[^-]*\)-.*:\1:' -e \
'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/')
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
sed -i.bak -e "1s/^/$BRANCH_NAME: /" $1
fi
@windgazer
Copy link
Author

Prep so that every repository on your machine gets this:

  1. git config --global init.templatedir '~/.git_template'
  2. N=~/.git_template/hooks/prepare-commit-msg ; curl -L https://goo.gl/5Mmuoi -o $N --create-dirs; chmod 744 $N
  3. For existing repositories run git init from the root of it, for new repositories, git clone will simply add the hook.

I understand you can also install it as a global hook that 'just works' for all repositories, but by the above setup you can also easily disable it for a couple of repositories by simply removing the hook after clone/init.

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