Skip to content

Instantly share code, notes, and snippets.

@erwan
Last active February 15, 2017 22:00
Show Gist options
  • Save erwan/4e0b5d4bee831af10fcaba7ad4cbb626 to your computer and use it in GitHub Desktop.
Save erwan/4e0b5d4bee831af10fcaba7ad4cbb626 to your computer and use it in GitHub Desktop.
pre-commit hook to prevent committing unwanted changes
#!/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
#
# Usage: save in .git/hooks/pre-commit of a given repository, and make executable
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