Skip to content

Instantly share code, notes, and snippets.

@EerdeBruining
Forked from aczietlow/prepare-commit-msg
Last active March 9, 2016 09:47
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 EerdeBruining/926eae54774c73bfb01a to your computer and use it in GitHub Desktop.
Save EerdeBruining/926eae54774c73bfb01a to your computer and use it in GitHub Desktop.
Git hook for prepare commit msg. Looks for an issue number in the branch name (a number between 3-9 digits long) and prepends it to the commit message in PivotalTracker style.
#!/bin/sh
#
# A hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg" and
# place it in .git/hooks.
#
# To enable this for all git projects use the global configuration
# 'init.templatedir'. Create a directory for git templates and a
# subdirectory for hooks.
# > mkdir -p ~/.git_template/hooks
# AM
# Use the following command to configure this as your git templates
# directory.
# > git config --global init.templatedir '~/.git_template'
# Place all global git hooks in '~/.git_template/hooks/'.
# In this instance it should be '~/.git_template/hooks/prepare-commit-msg'
# Give the git hooks the execute premission so they may run.
# > chmod +x ~/.git_template/hooks/prepare-commit-msg
#
# Now when you init a new git repo, the hook directory along with
# any hooks will automatically be placed in the new project git
# repo.
#
# You can also run 'git init' on an existing repo to have the
# reinitialized with new templates. To replace existing hooks, they must be removed from the repo before 'git ini
#
# Exit status of non zero will lead to a failed commit.
# Get the name of the branch in the current working tree.
NAME=$(git branch | grep '*' | sed 's/* //')
# Check the branch name for a 3 to 9 digit number (an issue number).
ISSUE_NUMBER=`echo "$NAME" | egrep -o '[0-9]{3,9}'`
# If branch contains a match for an issue number prepend the commit
# message with '[<issue_number>]: <commit message>.
if [ -n "$ISSUE_NUMBER" ]
then
if grep -q "\[#$ISSUE_NUMBER\]" "$1"; then
echo '';
else
printf "%s" "[#$ISSUE_NUMBER]: "|cat - "$1" >> /tmp/out && mv /tmp/out "$1";
fi
fi
@EerdeBruining
Copy link
Author

I changed the file to better support rebases etc.

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