Files
dotfiles/meta/git/hooks/pre-commit
druckdev 3c6c37f235 meta:hooks: Refactor pre-commit + check renaming
Refactor the script to match my coding style more and update the
comments.
When checking the filenames for non-ASCII characters, check also
renaming of files instead of only additions.
2020-10-24 20:04:30 +02:00

47 lines
1.4 KiB
Bash
Executable File

#!/bin/sh
#
# A 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.
#
# To enable this hook, save this file in ".git/hooks/pre-commit".
die() {
printf "$1" >&2
exit ${2:-1}
}
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
# Redirect output to stderr.
exec 1>&2
# Check that all filenames include only ASCII characters.
allownonascii=$(git config --bool hooks.allownonascii)
if [ "$allownonascii" != "true" ]; then
# 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.
num_nonascii=$(
git diff --cached --name-only --diff-filter=AR -z $against \
| LC_ALL=C tr -d '[ -~]\0' \
| wc -c
)
if [ $num_nonascii != 0 ]; then
printf "Rename files to only include ASCII characters.\n" >&2
die "Or set hooks.allownonascii to true.\n"
fi
fi
# Check for whitespace errors.
if ! git diff-index --check --cached $against --; then
die
fi