Prevent committing to master with git hooks
Currently, my git workflow consists of two branches: master and dev. The master branch is the last state of my code that was verified to work 100%. The dev branch is what I branch off of to fix bugs, add features, etc… (for very small changes I will work directly on dev). Sometimes I forget where I am, and I start coding on the master branch. In order to prevent myself from actually making commits to master I’ve added this code to my pre-commit hooks.
#!/bin/bash if [[ `git symbolic-ref HEAD` == "refs/heads/master" ]] then echo "You cannot commit to master!" echo "Stash your changes and apply them to another branch" echo "git stash" echo "git checkout branch" echo "git stash apply" exit 1 fi
This code runs right before each commit and prevents the commit if you are on the master branch. The error includes instructions on how to fix the issue by stashing your changes and applying them to a branch.
There are three ways to accomplish this:
-
Edit an existing repo’s pre-commit hook
Add the code to your pre-commit hook located in./.git/hooks/pre-commit -
Supply a template with the
--template=<template_directory>switch
This allows you to use a different template for creating the repo, instead of the default template. This also work when performing agit clone -
Edit your global template
The default global templates are located at /usr/share/git-core/templates. Add the code to thehooks/pre-commitfile located in that templates folder.
Personally, I’ve edited my global pre-commit hook. I don’t see a reason why I will ever need to commit to master.
This hook will prevent you from running a first commit on a newly created repo. Use the --no-verify option on a repo’s first commit to skip the pre-commit hook.
