Skip to content

Instantly share code, notes, and snippets.

@xTNTx
Created May 24, 2019 09:36
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 xTNTx/f119e7f67de245da459f596bb210f362 to your computer and use it in GitHub Desktop.
Save xTNTx/f119e7f67de245da459f596bb210f362 to your computer and use it in GitHub Desktop.
Enable git hook protection in master branch
  1. git config --global init.templatedir '~/.git-templates' - so git will copy all templates into new or cloned repository
  2. mkdir -p ~/.git-templates/hooks
  3. touch ~/.git-templates/hooks/pre-commit
  4. chmod +x ~/.git-templates/hooks/pre-commit
  5. Update ~/.git-templates/hooks/pre-commit with the following content

BRANCH="$(git rev-parse --abbrev-ref HEAD)"

MASTER_CHECK_ENABLED="$(git config --get custom.hooks.mastercheck || echo 'true')"

if [ "$BRANCH" = "master" ] && [ "$MASTER_CHECK_ENABLED" != "false" ]; then
  echo "\033[0;31mCommit failed!"
  echo "You can't commit directly to master branch.\033[0m"
  echo "Run \`git config custom.hooks.mastercheck false\` to disable the check for current repo."
  exit 1
fi
  1. Run git init in all repos you have already cloned. Done! This will not work if particular repo already has pre-commit hook. In that case just drop in bash part into existing script.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment