#Useful Git Hooks
Below are a couple of simple git hooks that can be useful for controlling and formatting commits. These are generally re-hashes of other people's ideas, so I've credited these as appropriate.
Git Hooks
A git hook is a script that lives in your
.git/hooks
directory. The scripts are invoked when certain events occur within your repo, such as make a commit or pushing changes. Hooks can be used to automate and augment basic actions within your repos.
##Include an issue number in your commit message
To amend your commit messages after they have been submitted, you'll need a commit-msg
hook. I borrowed most of these ideas from @monkseal. This hook assumes that your issue numbers are formatted into you branch names in a way that you can extract using a regex.
To create a hook, just create a file with the name of the hook (e.g.
commit-msg
) and put it in yourhooks
directory. The file does not need to have an extension.
#!/bin/sh
getIssueRef() {
# Amend the regex here to extract your issue reference from you're branch name.
git rev-parse --abbrev-ref HEAD | grep -e '[A-Z]\+-[0-9]\+' -o
}
MESSAGE="$(cat $1)"
TICKET=`getIssueRef`
if [ -n "$TICKET" ]
then
echo "New commit message: $TICKET : $MESSAGE"
# This line outputs the re-formatted commit message with the issue number in.
echo "$TICKET : $MESSAGE" > $1
fi
An alternative to re-formatting the commit messafge by prefixing it with the issue reference, might be to suffix it on a new line:
printf "$MESSAGE\n$TICKET" > $1
##Prevent commits from inadvertantly being made on master
If you want to prevent accidental commits to a local master branch, you can use a pre-commit
hook.
#!/bin/sh
currentBranch=`git rev-parse --abbrev-ref HEAD`
protectedBranch='master'
if [ $currentBranch = $protectedBranch ]
then
echo "Please do not commit directly to master. Create a topic branch and merge the change in GitHub"
exit 1
fi