Skip to content

Instantly share code, notes, and snippets.

@x0000ff
Last active December 20, 2021 16:14
Show Gist options
  • Save x0000ff/cb3297088636b74e7ca326d12c7a07fe to your computer and use it in GitHub Desktop.
Save x0000ff/cb3297088636b74e7ca326d12c7a07fe to your computer and use it in GitHub Desktop.
Prevent push to protected branches hook

Examples

Rejected
rejected
Approved
approved
Rejected custom branch
rejected-custom-branch
#!/bin/sh
# This script checks if you're pushing to any of protected branches and asks you to confirm your intention
#
# It detects even if you're trying to push to the branch with different name.
# Let's say that the current branch is 'feature' but you want to push to protected "release" branch.
# Next command push will be detected and the script will ask you to confirm the push
# $ git push -f origin HEAD:release
#
# To skip just add "--no-verify" argument:
# $git push --no-verify origin develop
#
# Edit "protected_branches" variables if you need:
# > protected_branches=('main' 'develop' 'release')
#
# Credits:
# * https://helloacm.com/how-to-prevent-commiting-to-master-develop-branch-by-accidents-using-pre-push-hooks-in-git/
# * https://gist.github.com/ColCh/9d48693276aac50cac37a9fce23f9bda#gistcomment-3178586
protected_branches=('develop')
if read local_ref local_sha remote_ref remote_sha; then
for protected_branch in "${protected_branches[@]}"
do
if [[ "$remote_ref" == *"$protected_branch"* ]]; then
echo "\033[1;33m⚠️ You're about to push to protected branch \"$protected_branch\", is that what you intended? [y|n] \033[0m"
echo "\033[1m"
read -n 1 -r < /dev/tty
echo "\033[0m"
# echo
if echo $REPLY | grep -E '^[Yy]$' > /dev/null; then
echo "👌 Exceptional push approved"
exit 0 # push will execute
fi
echo "✋ Aborted"
exit 1 # push will not execute
fi
done
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment