Skip to content

Instantly share code, notes, and snippets.

@eloisetaylor5693
Last active April 4, 2023 12:05
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 eloisetaylor5693/476e80628bfd6d9993ae8815ae3e32ae to your computer and use it in GitHub Desktop.
Save eloisetaylor5693/476e80628bfd6d9993ae8815ae3e32ae to your computer and use it in GitHub Desktop.
Git - ask before commiting to master/main

Outcome: you push to master/main, and get asked if you want to proceed

% git push
Are you sure you want to push to "main" ? (y/n): 

Instructions from here: https://gist.github.com/ColCh/9d48693276aac50cac37a9fce23f9bda

I preferred the script here though so used that instead: https://hammad.ca/blog/2015/03/08/confirm-before-pushing-to-master-branch

To install

  1. Enable git templates
git config --global init.templatedir '~/.git-templates'

  1. Create a directory to hold the global hooks:
mkdir -p ~/.git-templates/hooks
  1. Write your hook in ~/.git-templates/hooks

See file pre-push in this gist.

Copy it to ~/.git-templates/hooks/pre-push

  1. Make it executable
chmod a+x ~/.git-templates/hooks/pre-push
  1. In currently existing project, do reinit

git init

This will not overwrite existing commits, or existing hooks.

Done!

#!/bin/bash
# Warn before pushing to protected branches
# Make script executable with chmod +x pre-push
# Bypass with git push --no-verify
BRANCH=`git rev-parse --abbrev-ref HEAD`
PROTECTED_BRANCHES="^(master|main|dev|release-*|patch-*)"
if [[ "$BRANCH" =~ $PROTECTED_BRANCHES ]]; then
read -p "Are you sure you want to push to \"$BRANCH\" ? (y/n): " -n 1 -r < /dev/tty
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
exit 0
fi
echo "Push aborted."
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment