Add git pre-commit hook to catch nocommit lines (#22096)

Sometimes you’ll make a change to some code and not want to commit it. You probably add a comment to the code and hope you’ll either see the comment in the diff before committing or just remember not to check in the change. If you’ve ever done this you’ve probably also committed something you didn’t mean to commit. I know I have.

Below is a git pre-commit hook that searches for the text `nocommit` and if found rejects the commit. With it you can stick `nocommit` in a comment next to the change you don’t want committed and know that it won’t be committed.

You can maintain a list of personal forbidden words by exporting
`NOCOMMIT_RE` e.g:
`export NOCOMMIT_RE="spy|tap>|curse word"`
This commit is contained in:
Case Nelson
2022-04-27 12:35:53 -06:00
committed by GitHub
parent b233dc9ab1
commit 8108f0aa2d
2 changed files with 38 additions and 0 deletions

View File

@@ -2,3 +2,4 @@
. "$(dirname "$0")/_/husky.sh"
yarn precommit
./hooks/pre-commit.nocommit

37
hooks/pre-commit.nocommit Executable file
View File

@@ -0,0 +1,37 @@
#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=$(git hash-object -t tree /dev/null)
fi
# Redirect output to stderr.
exec 1>&2
# Check user defined nocommit words
if [ -z "$NOCOMMIT_RE" ]; then
RE="nocommit"
else
RE="nocommit|$NOCOMMIT_RE"
fi
NOCOMMIT_FOUND=$(git diff --cached --diff-filter=ACM $against | egrep -i "$RE")
if [ -z "$NOCOMMIT_FOUND" ]; then
exit 0
else
echo "\033[2m$ $(readlink -f $0)\033[0m"
echo "File(s) being committed matching '$RE' (add --no-verify to ignore):"
for f in $(git diff --cached --name-only --diff-filter=ACM $against); do
FILE_DIFF=$(git diff --cached --diff-filter=ACM $against -- $f | egrep -i "$RE")
if [ -z "$FILE_DIFF" ]; then
true
else
echo "\t$f"
fi
done
exit 1
fi