Skip to content

Instantly share code, notes, and snippets.

@GUI
Forked from mosra/README.md
Last active August 17, 2020 19:55
Show Gist options
  • Save GUI/676bcb25389cd01d47828fddcf37e1f2 to your computer and use it in GitHub Desktop.
Save GUI/676bcb25389cd01d47828fddcf37e1f2 to your computer and use it in GitHub Desktop.
Git pre-push hook to confirm pushing to master

Git pre-push hook

Checks if the remote branch is master, then asks a confirmation. Based on https://gist.github.com/ColCh/9d48693276aac50cac37a9fce23f9bda, but with updated instructions for Git 2.9+ with global hooks.

Further info: https://dev.ghost.org/prevent-master-push/, https://coderwall.com/p/jp7d5q/create-a-global-git-commit-hook, https://git-scm.com/docs/githooks#_pre_push, https://stackoverflow.com/questions/22585091/git-hooks-pre-push-script-does-not-receive-input-via-stdin

Installation

  1. Check your git version. 2.9 or higher is needed for configuring global git hooks.

    git --version
  2. Create a directory to hold the global hooks:

    mkdir ~/.git-hooks-global
  3. Copy the pre-push file from below into ~/.git-hooks-global/pre-push and make it executable:

    curl -o ~/.git-hooks-global/pre-push https://gist.githubusercontent.com/GUI/676bcb25389cd01d47828fddcf37e1f2/raw/3110c99b9ef17639a14a0b442d87d1db6ff7a569/pre-push && chmod +x ~/.git-hooks-global/pre-push
  4. Configure the global git hooks path:

    git config --global core.hooksPath ~/.git-hooks-global

Done!

#!/bin/bash
protected_branch='master'
# Argument parsing taken from .git/hooks/pre-push.sample
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment