#!/bin/bash
#
# Hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.

[ -n "$GIT_DIR" ] || export GIT_DIR="$(git rev-parse --show-toplevel 2>/dev/null)/.git"
. "$GIT_DIR"/hooks/hook_lib

# What are we diffing this commit against?
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

step_name 'Checking for non-ASCII filenames'
# We exploit the fact that the printable range starts at the space character
# and ends with tilde.
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
added_files=$(git diff --cached --name-only --diff-filter=A -z $against | tr '\0' ' ')
added_files_array=(`echo $added_files`)
# Print the files that have non-ascii text
for i in ${added_files_array[@]}; do
  bad_chars=$(echo -n $i | LC_ALL=C tr -d '[ -~]\0')
  if [ -n "$bad_chars" ]; then echo $i; fi
done
# Fail if any non-ASCII characters are discovered
(echo -n $added_files | LC_ALL=C tr -d '[ -~]\0' | exit $(wc -c))
check_rc "Rename non-ASCII file name(s) before committing"

step_name 'Checking for trailing whitespace in non-Ruby files'
# If there are whitespace errors, print the offending file names and fail.
# Ignore .rb files, as whitespace in these files is managed by Rubocop
# Ignore .proto files, as they are generated code
non_ruby_files=`git diff --staged --name-only | grep -v \.rb | grep -v \.proto`
if [ -n "$non_ruby_files" ]; then
  ! git grep -n -I '\s$' -- $non_ruby_files
  check_rc "Fix trailing whitespace before committing"
fi
