Created
June 13, 2023 15:22
-
-
Save sjagoe/52102d7863024c43d08a2bbbf3595e5f to your computer and use it in GitHub Desktop.
git global pre-push hook to prevent accidental push to main branch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
RED="\033[31m"; | |
RESET="\033[0m"; | |
BOLD="\033[1m"; | |
ppid_is_emacs() { | |
local command= | |
command="$(ps ho comm "$1")" | |
[[ "$command" =~ .*emacs.* ]] | |
} | |
is_emacs() { | |
local temp_ppid= | |
temp_ppid="$(ps ho ppid "$1")" | |
local ppid="${temp_ppid// /}" | |
ppid_is_emacs "$ppid" && return 0 | |
[ "$ppid" -eq 1 ] && return 1 | |
is_emacs "$ppid" && return 0 | |
return 1 | |
} | |
protected_branch="$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed -e 's/^refs\/remotes\/origin\///')" | |
current_branch=$(git symbolic-ref HEAD | sed -e 's,^refs/heads/,,') | |
REPLY=n | |
if [[ "$protected_branch" == "" ]]; then | |
echo -en "${BOLD}${RED}Can't determine default branch. Continue to push anyway? [y|n] ${RESET}" | |
echo -en "${BOLD}" | |
if is_emacs "$$"; then echo n; exit 1; fi | |
read -n 1 -r < /dev/tty | |
echo -en "${RESET}" | |
elif [ "$protected_branch" == "$current_branch" ]; then | |
echo -en "${BOLD}${RED}You're about to push directly to $protected_branch, is that what you intended? [y|n] ${RESET}" | |
echo -en "${BOLD}" | |
if is_emacs "$$"; then echo n; exit 1; fi | |
read -n 1 -r < /dev/tty | |
echo -en "${RESET}" | |
else | |
exit 0 # push will execute | |
fi | |
echo | |
if echo $REPLY | grep -E '^[Yy]$' > /dev/null | |
then | |
exit 0 # push will execute | |
fi | |
exit 1 # push will not execute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment