Skip to content

Instantly share code, notes, and snippets.

@sloev
Forked from ColCh/README.md
Last active February 28, 2022 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sloev/9064296899ef8cd12d3061e569ee7064 to your computer and use it in GitHub Desktop.
Save sloev/9064296899ef8cd12d3061e569ee7064 to your computer and use it in GitHub Desktop.
Git pre-push hook to confirm pushing to master

Git pre-push hook

It will check if current branch is master, then ask a confirmation, in case of master branch

install

  1. install a recent version of git (https://git-scm.com/download/mac) eg:
    $ brew install git
    $ echo 'alias git="/us/bin/local"' >> ~/.zshrc
  2. create global git hooks directory
    $ mkdir ~/.githooks
  3. save the pre-push script beneith in ~/.githooks/pre-push
  4. make it executable: chmod +x ~/.githooks/pre-push
  5. tell git how to find it:
    $ git config --global core.hooksPath /Users/Someone/.githooks/

example:

$ foo@somewhere something  > git push
You're about to push to master, is that what you intended? [y|n] n
error: failed to push some refs to 'github.com:someone/something.git'
$ foo@somewhere something  >
#!/bin/bash
protected_branch='master'
if read local_ref local_sha remote_ref remote_sha; then
if [[ "$remote_ref" == *"$protected_branch"* ]]; then
echo -en "\033[1;33mYou're about to push to master, is that what you intended? [y|n] \033[0m"
echo -en "\033[1m"
read -n 1 -r < /dev/tty
echo -en "\033[0m"
echo
if echo $REPLY | grep -E '^[Yy]$' > /dev/null; then
exit 0 # push will execute
fi
exit 1 # push will not execute
fi
fi
@dvnlgls
Copy link

dvnlgls commented Jan 11, 2022

This is great. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment