Last active
September 26, 2024 08:35
-
-
Save arturadib/97a17752301ee796f9a0 to your computer and use it in GitHub Desktop.
Pre-commit hook to prevent debug code from being committed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Paste this script in your .git/hooks/pre-commit file (create one if it doesn't exist yet) | |
# To prevent debug code from being accidentally committed, simply add a comment near your | |
# debug code containing the keyword !nocommit and this script will abort the commit. | |
# | |
if git commit -v --dry-run | grep '!nocommit' >/dev/null 2>&1 | |
then | |
echo "Trying to commit non-committable code." | |
echo "Remove the !nocommit string and try again." | |
exit 1 | |
else | |
exit 0 | |
fi |
After I forgot to add sign !
(and pushed it...) I tuned first line to if git diff --staged | grep -E -i -w '(!)?no(-| )?commit' >/dev/null 2>&1
This will allow combinations like !nocommit
, nocommit
, NOCOMMIT
, !No-Commit
, No Commit
etc.
Total script (which I use on Windows):
#!/bin/bash
#
# To prevent debug code from being accidentally committed, simply add a comment near your
# debug code containing the keyword "// NOCOMMIT" or "// !nocommit" (case insensitive) or "// !no-commit" or "// !no commit"
# and this script will abort the commit.
#
echo "Checking non-committable code..."
if git diff --staged | grep -E -i -w '(!)?no(-| )?commit' >/dev/null 2>&1
then
echo "You are trying to commit non-committable code."
echo "Remove the NOCOMMIT string and try again."
exit 1
else
# Run local pre-commit hook if exists
if [ -e ./.git/hooks/pre-commit ]; then
./.git/hooks/pre-commit "$@"
else
exit 0
fi
fi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very usefull, thanks !