Skip to content

Instantly share code, notes, and snippets.

@spacechurro
Last active February 19, 2021 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spacechurro/3939f2c12806ef1e0b123367956e79f4 to your computer and use it in GitHub Desktop.
Save spacechurro/3939f2c12806ef1e0b123367956e79f4 to your computer and use it in GitHub Desktop.
auto-installed git hooks for new repos with git templates

Here is how you can have some default git hooks auto installed with every new repo you clone. I use this to install a pre-push hook that adds a confirmation step to any push to main so that I don't accidentally push up any changes.

  1. set up git to use a templatedir
git config --global init.templatedir '~/.git_template'
mkdir -p ~/.git_template/hooks
  1. add in the pre-push hook code in .git_template/hooks/pre-push
#!/bin/bash

protected_branch='main'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [ $protected_branch = $current_branch ]
then
    read -p "You're about to push main, 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
else
    exit 0 # push will execute
fi
  1. make sure the new hook is marked as executable by running chmod +x pre-push on command line

  2. profit.

credits

Stole the git template setup from the vim king, Tim Pope. https://tbaggery.com/2011/08/08/effortless-ctags-with-git.html

Stole the pre-push hook from Ghost CTO, Hannah Wolfe. http://dev.ghost.org/prevent-master-push/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment