Skip to content

Instantly share code, notes, and snippets.

@sjagoe
Created June 13, 2023 15:22
Show Gist options
  • Save sjagoe/52102d7863024c43d08a2bbbf3595e5f to your computer and use it in GitHub Desktop.
Save sjagoe/52102d7863024c43d08a2bbbf3595e5f to your computer and use it in GitHub Desktop.
git global pre-push hook to prevent accidental push to main branch
#!/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