Skip to content

Instantly share code, notes, and snippets.

@spudfkc
Created October 31, 2013 19:37
Show Gist options
  • Save spudfkc/7255545 to your computer and use it in GitHub Desktop.
Save spudfkc/7255545 to your computer and use it in GitHub Desktop.
prevents committing to certain git branches. I made this because I would accidentally commit to master instead of a feature branch. This could cause a mess with dependencies and gerrit. Not committing to master was the easiest solution for that. How To Use: put this in <repo>/.git/hooks/pre-commit
#!/bin/bash
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
array_contains() {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"
do
if [[ $element == $seeking ]]
then
in=0
break
fi
done
return $in
}
# These are branches that should not be committed to directly
UNALLOWED_BRANCHES=("master" "air" "5.0" "6.0" "4.8")
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
currentbranch=$(git branch --color=NEVER | grep "*" | awk '{print $2}')
array_contains UNALLOWED_BRANCHES $currentbranch && branchok="false" || branchok="true"
# If you want to allow committing on master branch set this variable to true
allowmastercommit=$(git config hooks.allowmastercommit)
# Redirect output to stderr.
exec 1>&2
if [ "$allowmastercommit" != "true" ] && [ "$branchok" == "false" ]
then
echo "Error: Attempt to commit to an unallowed branch: $currentbranch"
echo
echo "Use a feature branch instead."
echo "Disable this check by using:"
echo
echo " git config hooks.allowmastercommit true"
echo
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment