Skip to content

Instantly share code, notes, and snippets.

@bps
Created February 1, 2010 16:28
Show Gist options
  • Save bps/291796 to your computer and use it in GitHub Desktop.
Save bps/291796 to your computer and use it in GitHub Desktop.
A git pre-commit hook to stop you from committing scratch code.
#!/bin/sh
# A hook to abort a commit if your diff adds XXX or FIXME.
# Set this config variable if you want to allow it anyway.
allowfixmes=$(git config hooks.allowfixmes)
disallow_list="XXX FIXME"
if [ "$allowfixmes" != "true" ]
then
for disallow in $disallow_list
do
if [ "$(git diff --cached | egrep "^\+.*${disallow}" > /dev/null; echo $?)" -eq "0" ] # egrep exits with 0 if it finds at least one match
then
echo "Error: Your diff will commit ${disallow}:"
echo
git diff --cached -S"${disallow}"
echo
echo "To commit anyway, use \`git config --bool hooks.allowfixmes true\`"
echo "to set the config variable that skips this check."
exit 1
fi
done
fi
# Nothing disallowed added. Allow commit.
exit 0
@Grandmother
Copy link

Hi, you have a mistake in 12th string. You can't nest quotes in such manner.

@bps
Copy link
Author

bps commented Aug 13, 2019

Under which shell did it fail for you? It works for me in zsh 5.4.2 and bash 4.4.20. Command substitution starts a new quoting context. See https://mywiki.wooledge.org/CommandSubstitution for some detail.

The bug is in line 1 in not specifying bash. If your platform ships an actual Bourne shell, it will fail on line 5.

@Grandmother
Copy link

I'm sorry. It's definitely not because of quotes. Now I tested it little bit more accurate and found that it works when I switch off color in diff.

So now I have this line in my pre-commit hook:

if [ "$(git diff --color=never --cached | egrep "^\+.*${disallow}" > /dev/null; echo $?)" -eq "0" ]

@Grandmother
Copy link

And now changed color configuration in .gitconfig from "always" to "auto" and it works even without --color=never in pre-commit hook.

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