Skip to content

Instantly share code, notes, and snippets.

@lyoshenka
Forked from greglboxer/pre-push.sh
Last active June 14, 2023 06:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lyoshenka/158cfff41d09e1dcf029 to your computer and use it in GitHub Desktop.
Save lyoshenka/158cfff41d09e1dcf029 to your computer and use it in GitHub Desktop.
Git pre-push hook to prevent force-pushing or deleting a special branch (e.g. master)
#!/bin/bash
# Requires git 1.8.2 or newer
# Prevents force-pushing or deleting a special branch (e.g. master).
# Based on: https://gist.github.com/pixelhandler/5718585 and https://gist.github.com/stefansundin/d465f1e331fc5c632088
# Install:
# cd path/to/git/repo
# curl -fL -o .git/hooks/pre-push https://gist.githubusercontent.com/lyoshenka/158cfff41d09e1dcf029/raw/pre-push.sh
# chmod +x .git/hooks/pre-push
PROTECTED_BRANCH='master'
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
PUSH_COMMAND=$(ps -ocommand= -p $PPID)
IS_DESTRUCTIVE='\-\-force|\-\-delete|\-f'
WILL_DELETE_PROTECTED_BRANCH=" :$PROTECTED_BRANCH"
if [[ $PUSH_COMMAND =~ $IS_DESTRUCTIVE ]] && ( [ $CURRENT_BRANCH = $PROTECTED_BRANCH ] || [[ $PUSH_COMMAND =~ $PROTECTED_BRANCH ]] ) ||
[[ $PUSH_COMMAND =~ $WILL_DELETE_PROTECTED_BRANCH ]]; then
echo -e "\n[PRE-PUSH HOOK ERROR] Do not force-push or delete the \"$PROTECTED_BRANCH\" branch!\n"
# you can skip this check with --no-verify
exit 1
fi
exit 0
#!/bin/sh
# This script will install a Git pre-push hook that prevents force pushing the master branch.
# Install in current Git repo:
# curl -fL https://gist.githubusercontent.com/lyoshenka/158cfff41d09e1dcf029/raw/z-pre-push-installer.sh | bash
# Uninstall:
# rm .git/hooks/pre-push
# in each repository that you've added this to.
GITROOT=`git rev-parse --show-toplevel 2> /dev/null`
echo
echo
if [ "$GITROOT" == "" ]; then
echo This does not appear to be a git repo.
exit 1
fi
if [ -f "$GITROOT/.git/hooks/pre-push" ]; then
echo There is already a pre-push hook installed. Delete it first.
echo
echo " rm '$GITROOT/.git/hooks/pre-push'"
echo
exit 2
fi
echo Downloading pre-push hook from https://gist.github.com/lyoshenka/158cfff41d09e1dcf029
echo
curl -fL -o "$GITROOT/.git/hooks/pre-push" "https://gist.githubusercontent.com/lyoshenka/158cfff41d09e1dcf029/raw/pre-push.sh"
if [ ! -f "$GITROOT/.git/hooks/pre-push" ]; then
echo Error downloading pre-push script!
exit 3
fi
chmod +x "$GITROOT/.git/hooks/pre-push"
echo "You're all set! Happy hacking!"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment