Přeskočit na obsah

Používáte-li jako já u některých projektů git push pro odesílání aktuální verze projektu na produkci nebo staging, může se vám hodit následující gist. Jedná se o pre-push hook, který vás ochrání před lidskou chybou v deployi. Pokud pushujete na jiný remote než na origin (např. production nebo staging), tak se vás zeptá, jestli to tam opravdu chcete nahrát.

Jednou jsem omylem stagingovou (naštěstí finální) verzi poslala na produkci a už nechci, aby se to opakovalo.

#!/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 rawpre-push hosted with ❤ by GitHub