GIT Hook to prevent Commit of a file
This is one of my favorite tricks.
When I make a temporary change to code, usually for testing, that I do not want to commit, I simply add a comment above the temporary code with the words DO NOT COMMIT. When I try to commit that file, git will abort the commit and warn me:
+ // DO NOT COMMIT
pre-commit: Blocking commit because detect
In the root of your project, open the hidden .git folder.
Use CMD + SHIFT + .
to toggle display of hidden files if needed.
If it doesn’t exist, create a hooks subfolder.
create a file named pre-commit with the following content:
#!/bin/sh
# Check if this is the initial commit
if git rev-parse –verify HEAD >/dev/null 2>&1
then
against=HEAD
else
echo “pre-commit: About to create the first commit…”
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi# Use git diff-index to check for @DONTCOMMITTHIS
# http://stackoverflow.com/a/7292992/3307822
# https://www.atlassian.com/git/tutorials/git-hooks/local-hooks
#
declare -a strsToLookForArr=(
“DONTCOMMITTHIS”
“DONOTCOMMIT”
“DO NOT COMMIT”
)for str in “${strsToLookForArr[@]}”
do
if git diff-index -p -M –cached $against — | grep ‘^+’ | grep -i “$str”
then
echo “pre-commit: Blocking commit because $strToLookFor detected”
exit 1
fi
doneecho “pre-commit: clear”
exit 0