Skip to content

Instantly share code, notes, and snippets.

@erwan
Created May 30, 2017 12:46
Show Gist options
  • Save erwan/d200bcf608316bb13448ab9e811408b8 to your computer and use it in GitHub Desktop.
Save erwan/d200bcf608316bb13448ab9e811408b8 to your computer and use it in GitHub Desktop.
pre-commit to reject stop words
#!/bin/sh
# Reject commits on some stop words:
# nocommit: include this word (in a comment) when you're doing a local change that should not be committed
# fdescribe: used in jasmine to run a single test
declare -a stopwords=("nocommit" "fdescribe")
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
patch_filename=$(mktemp -t commit_hook_changes.XXXXXX)
git diff --exit-code --binary --ignore-submodules --no-color > $patch_filename
has_unstaged_changes=$?
if [ $has_unstaged_changes -ne 0 ]; then
echo "Stashing unstaged changes in $patch_filename."
git checkout -- .
fi
quit() {
if [ $has_unstaged_changes -ne 0 ]; then
git apply $patch_filename
if [ $? -ne 0 ]; then
git checkout -- .
git apply $patch_filename
fi
fi
exit $1
}
# Redirect output to stderr.
exec 1>&2
for word in "${stopwords[@]}"
do
files_with_word=$(git diff --cached --name-only --diff-filter=ACM $against | xargs grep -i "$word" -l | tr '\n' ' ')
if [ "x${files_with_word}x" != "xx" ]; then
tput setaf 1
echo "File being committed with '$word' in it:"
echo $files_with_word | tr ' ' '\n'
tput sgr0
quit 1
fi
done
quit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment