Skip to content

Commit

Permalink
Add git pre-commit hook to catch nocommit lines (metabase#22096)
Browse files Browse the repository at this point in the history
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"`
  • Loading branch information
snoe authored Apr 27, 2022
1 parent b233dc9 commit 8108f0a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
. "$(dirname "$0")/_/husky.sh"

yarn precommit
./hooks/pre-commit.nocommit
37 changes: 37 additions & 0 deletions hooks/pre-commit.nocommit
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 8108f0a

Please sign in to comment.