Skip to content

Instantly share code, notes, and snippets.

@malesch
Last active August 29, 2015 14:19
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 malesch/e15b0bc814250777fae6 to your computer and use it in GitHub Desktop.
Save malesch/e15b0bc814250777fae6 to your computer and use it in GitHub Desktop.
Validation Git precommit hock
#!/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=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
files=( $(git diff --cached --name-only $against) )
for f in "${files[@]}"; do
commit_file=$f
filename=$(basename "$commit_file")
ext="${filename##*.}"
##
# TODO: Skip validations if binary content or enable
# only for certain file extensions (.rb, .erb,...) and
# files (Gemfile, Rakefile,...), respectively
#
##
# Collect line numbers of locations violating...
#
violations=false
# End-of-line rule (only \n allowed)
lines=( $(grep -n -IU $'\r' $commit_file | cut -f1 -d:) )
if [ ${#lines[@]} -gt 0 ]; then
violations=true
echo
echo "!!! End-of-line violations in '${commit_file}' !!!"
for n in "${lines[@]}"; do
echo " line ${n}"
done
fi
# Trailing whitespaces
lines=( $(grep -n -E "\s+$" $commit_file | cut -f1 -d:) )
if [ ${#lines[@]} -gt 0 ]; then
violations=true
echo
echo "!!! Trailing whitespaces in '${commit_file}' !!!"
for n in "${lines[@]}"; do
echo " line ${n}"
done
fi
# Merge conflict markers
lines=( $(grep -n -E "^(<{7}|={7}|>{7})" $commit_file | cut -f1 -d:) )
if [ ${#lines[@]} -gt 0 ]; then
violations=true
echo
echo "!!! Merge conflict markers in '${commit_file}' !!!"
for n in "${lines[@]}"; do
echo " line ${n}"
done
fi
# Active debugger commands
# Restriction: Does not check for multi-line comments (=begin...=end)
# bash:
# a='apples, pears ; and bananas'
# b='apples, pears # and bananas'
# echo ${a%%;*}
# echo ${b%%#*}
# sed:
# echo "$1" | sed 's/ *[#;].*$//g' | sed 's/^ *//'
# Only check Ruby enabled sources (.rb, .erb) for debugger commands
ruby_file_ext=(rb erb)
if [[ ${ruby_file_ext[*]} =~ $ext ]]; then
lines=( $( cat $commit_file | sed 's/ *[#;].*$//g' | sed 's/^ *//' | \
grep -n -E "\bbinding\.pry\b|\bdebugger\b" \
| cut -f1 -d:) )
if [ ${#lines[@]} -gt 0 ]; then
violations=true
echo
echo "!!! Debugger command(s) in '${commit_file}' !!!"
for n in "${lines[@]}"; do
echo " line ${n}"
done
fi
fi
# TODO: Check .slim sources for Ruby/debugger statements
# (Ruby statements enabled with preceding '-')
done
# Exist with error status if violations exist
if [ "$violations" = true ]; then
exit 1;
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment