How to use git hooks for everyday tasks
Git hooks is a feature that does not get talked about enough. Basically hooks are a way to trigger an action during certain parts of git's execution.
By default hooks are placed in .git/hooks. You can change this in git config. I wont go into details about each of the hook types. You can find the description here -https://githooks.com/
We will take a look at some practical examples on how to use the hooks.
Prevent commit
You need to place this in file .git/hooks/pre-commit
#!/bin/sh branch=`git symbolic-ref HEAD` if [ "$branch" = "refs/heads/master" ]; then echo "Commit is not allowed" exit 1 fi exit 0
There is a lot to talk about here. You can specify the branch you want to restrict. Usually this is helpful for projects where you do not want anyone committing from production environment.
Prevent push
Similarly if you want to prevent pushing to a branch you can use the pre-push hook. Place it in .git/hooks/pre-push.
#!/bin/sh # Prevent push to remote master branch while read local_ref local_sha remote_ref remote_sha do if [ "$remote_ref" = "refs/heads/master" ]; then echo "pre-push hook: Can not push to remote master branch." exit 1 fi done exit 0
Send an alert
Once you are hooked into the event you can trigger anything you want. For example you might want to send an email once someone is triggering the action:
#!/bin/sh branch=`git symbolic-ref HEAD` if [ "$branch" = "refs/heads/staging" ]; then echo "Someone just commited something to staging. Take a look on https://techflarestudio.com/" | mail -s "Staging notification" info@techflarestudio.com fi exit 0
Here we are sending an email but really the possibilities are endless. Let us know if you find this useful or have anything to add.