Skip to content

Instantly share code, notes, and snippets.

@djromero
Last active December 2, 2015 16:50
Show Gist options
  • Save djromero/c76548470866ffcc3e9c to your computer and use it in GitHub Desktop.
Save djromero/c76548470866ffcc3e9c to your computer and use it in GitHub Desktop.
Git pre-commit hook to detect debugging stuff that shouldn't be commited.
#!/bin/sh
# commit without hook:
# git commit --no-verify
#
declare -i REJECTED
REJECTED=0
red="\033[31m"
reset="\033[m"
bold="\033[1m"
git stash -q --keep-index
# detect forbidden strings
while read path
do
if [ "${path}" != "" ] ; then
diff=`git diff --cached | grep ^+`
if [[ -n $diff ]] ; then
forbidden=`echo "${diff}" | \
GREP_COLOR='4;5;37;41' grep -E \
--regexp='DO NOT COMMIT' \
--regexp='#del'
`
if [[ -n $forbidden ]] ; then
REJECTED=1
echo ${bold}${path}
echo ${reset}${forbidden}
echo
fi
fi
fi
done <<< `git diff --cached --name-only | egrep '\.(swift|h|m)$'`
git stash pop -q
if [ $REJECTED -eq 1 ] ; then
echo ${red}${bold}⚠️" REJECTED COMMIT"
echo ${red}Found forbidden strings.${reset}
exit 1
fi
exit 0
@djromero
Copy link
Author

djromero commented Nov 5, 2015

I wrap experimental or debugging code with this (using an Xcode snippet):

#warning /////////////////////// DO NOT COMMIT { //////////////////////////////
<#here#>
#warning /////////////////////// } DO NOT COMMIT //////////////////////////////

Then, when I forget to remove them, this is what I see:

rejected-commit

And the commit is aborted.

I use tig or just the command line for commits. I didn't test the hook with a GUI git client.

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