Prevent pushing to main branch

Use a .git hooks script to prevent accidentally pushing to main branch

Aug 15, 2021 1 min read

Oops, I just pushed to main!

Pushing to main branch when you meant to push to a new feature branch is embarrassing and annoying.

Github has a great per repo setting called “Branch protection rules” that can prevent your team from accidentally pushing to main (or master) branch. And also ensure that status checks like tests and linters all pass.

If you don’t have this set. Or if you’re an admin that’s allowed to override failed checks, nothing prevents you from pushing to main.

Git hooks to the rescue

cat << 'DOC' > .git/hooks/pre-push

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [ $protected_branch = $current_branch ]
    read -p "You're about to push to $protected_branch, is that what you intended? [y|n] " -n 1 -r < /dev/tty
    if echo $REPLY | grep -E '^[Yy]$' > /dev/null
        exit 0 # push will execute
    exit 1 # push will not execute
    exit 0 # push will execute

chmod +x .git/hooks/pre-push
Read more posts like this in the Software Engineering Toolbox collection.
Visit homepage
comments powered by Disqus