Skip to content

Instantly share code, notes, and snippets.

@Kintull
Created March 9, 2017 14:05
Embed
What would you like to do?
Git pre-commit hook to prevent non-ascii characters in C, C++, Erlang source code files
#!/bin/bash
#cp pre-commit .git/hooks/pre-commit
#chmod +x .git/hooks/pre-commit
filelist=`git diff HEAD --name-only --relative | grep -E '\.(c|h|cc|hh|cpp|erl|hrl|idl)$'`
abort='false'
for filename in $filelist
do
output=`git diff HEAD -- $filename | grep ^+[^+] | tr -d "\000-\011\013-\177" | tr -d '\n'`
cnt=${#output}
if [ -n "$output" ]; then
if [ $abort == 'false' ]; then
echo -e "\nAborting commit! Non ascii character(s) found in change set:\n"
fi
for ((i=0; i < cnt; i++))
do
char=${output:$i:1}
echo -e "\nFound '$char' in file '$filename':\n"
git diff HEAD -S$char
done
abort='true'
fi
done
if [ $abort == 'true' ]; then
echo -e "\nYou can skip pre-commit check with 'git commit --no-verify'"
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment