Blog /

Git: pre-push confirmation

Git pre-push hook that will prompt a confirmation y/n question before pushing to remote but origin.

Are you using git push for deploying the project to production or staging (for example, on WP Engine)? If the answer is yes, you might find the following gist handy. It’s a pre-push hook that will prompt a confirmation y/n question before pushing to remote but origin.

Once, I’ve sent the staging version to the production and never more.


#!/bin/sh
# An additional confirmation if you really want to push to remote (prevents accidental pushes).
#
# This hook is called with the following parameters:
#
# $1 — Name of the remote to which the push is being done
# $2 — URL to which the push is being done
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
remote="$1"
url="$2"
# If we have a STDIN, use it, otherwise get one
if tty >/dev/null 2>&1; then
TTY=$(tty)
else
TTY=/dev/tty
fi
# http://djm.me/ask
ask() {
while true; do
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
# Ask the question (not using "read -p" as it uses stderr not stdout)
echo -n "$1 [$prompt] "
# Read the answer
read REPLY < "$TTY"
# Default?
if [ -z "$REPLY" ]; then
REPLY=$default
fi
# Check if the reply is valid
case "$REPLY" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
# Test the push branch
while read local_ref local_sha remote_ref remote_sha
do
# Exit if pushed to origin
if [ "$remote" != "origin" ]
then
# Check if not pushing accidentaly
printf "\n"
if ask "Do you really want to push to $remote?"; then
printf 'Pushing.\n\n'
else
printf "Cancelling.\n\n"
exit 1
fi
fi
done
exit 0

view raw

pre-push

hosted with ❤ by GitHub