Skip to content

Instantly share code, notes, and snippets.

@aks
Created July 20, 2017 17:16
Show Gist options
  • Save aks/a6f56f2c3f9d4e19ca8a136d3e726530 to your computer and use it in GitHub Desktop.
Save aks/a6f56f2c3f9d4e19ca8a136d3e726530 to your computer and use it in GitHub Desktop.
Bash script to install a `pre-push-hook` into the current git repo
#!/usr/bin/env bash
# install-pre-push-hook
# this script installs the pre-push hook into the current .git repo.
# by default, the pre-push hook protects the "master" branch.
set_git_hooks_dir_path() {
set_git_dir_path
git_hooks_dir_path="$git_dir_path/hooks"
if [[ ! -d "$git_hooks_dir_path" ]] ; then
echo 1>&2 "$git_hooks_dir_path does not exist!"
exit
fi
}
set_git_dir_path() {
local dir_path=`git rev-parse --git-dir`
git_dir_path=`absolute_path "$dir_path"`
if [[ ! -d "$git_dir_path" ]]; then
echo 1>&2 "Not in a repo!"
exit
fi
}
absolute_path() {
case "$1" in
/*) echo "$1" ;;
*) echo "`pwd`/$1" ;;
esac
}
install_pre_push_script() {
set_git_hooks_dir_path
pre_push_path="$git_hooks_dir_path/pre-push"
if [[ -e "$pre_push_path" ]] ; then
mv "$pre_push_path" "$pre_push_path.old"
fi
create_pre_push_script "$pre_push_path"
}
create_pre_push_script() {
local dest_path="$1"
cat <<'EOF' >"$dest_path"
#!/bin/bash
protected_branch='master'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ $protected_branch = $current_branch ] ; then
read -p "You're about to push master, is that what you intended? [y|n] " -n 1 -r < /dev/tty
echo
if echo $REPLY | grep -E '^[Yy]$' > /dev/null ; then
exit 0 # push will execute
fi
exit 1 # push will not execute
fi
exit 0 # push will execute
EOF
chmod +x $dest_path
echo 1>&2 "Created $dest_path"
}
install_pre_push_script
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment