Skip to content

Instantly share code, notes, and snippets.

@chrisfrancis27
Created February 17, 2016 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfrancis27/e50a1ef48b111fc1ee1a to your computer and use it in GitHub Desktop.
Save chrisfrancis27/e50a1ef48b111fc1ee1a to your computer and use it in GitHub Desktop.
Git pre-commit hook for warning about new occurrences of a string, e.g. "// TODO"
#!/bin/bash
# Change $stopword to whatever string you want to disallow
# N.B. It's going into a regex, so don't be ridiculous.
stopword="TODO"
########################################
# You shouldn't need to touch anything #
# below this line #
########################################
# Redirect output to stderr.
exec 1>&2
# enable user input
exec < /dev/tty
# Count all matches in added/modified lines (excluding filenames) in the current patch
count=$(git diff --cached | grep -e "^+" | grep -v "^+++" | grep -e $stopword | wc -l)
# CHECK
if test $count != 0
then
echo -e "\n\033[0;31mWarning: You've added $(echo $count) occurences of \"$(echo $stopword)\" since the last commit!\n\033[0m";
# Backup IFS delimiter
OLD_IFS="$IFS";
# Only split on newlines, not normal whitespace
IFS=$'\n';
# Get filenames of all files containing additions/modifications, and get stopword matches
matches=($(git diff --cached | grep --color=never -e "^+++" -e "^@@" -e "^+.*$stopword"));
# Restore previous IFS delimiter
IFS="$OLD_IFS";
# Loop over each result
filename="";
startline=0;
endline=0;
for i in "${matches[@]}"
do
if test $(echo $i | grep -e "^+++" | wc -l) != 0
then
# Strip out filename from unified diff header line,
# e.g. `+++ b/config/env/local.js`
filename=$(echo $i | sed "s/+++ [ab]\///");
elif test $(echo $i | grep -e "^@@" | wc -l) != 0
then
# Strip out new line numbers from hunks header,
# e.g. `@@ -18,6 +19,8 @@ ...`
lines=$(echo $i | sed "s/^[^+]*+\([0-9]*,[0-9]*\).*/\1/");
startline=$(echo $lines | sed "s/,.*//");
endline=$(echo $lines | sed "s/[^,]*,//");
endline=$(( $startline + $endline ))
else
excerpt=$(echo $i | sed "s/+\s*//");
echo -e "\033[0;34m$filename \033[0;33m($startline-$endline): \033[0;37m$excerpt\033[0m";
fi
done
echo -e "\033[0;36m";
read -p "Are you sure want to continue (y/N)? " -n1 yn
echo -e "\033[0m";
echo $yn | grep -iq ^y$
if [ $? -eq 0 ]
then
exit 0;
else
echo "Commit aborted.";
exit 1;
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment