Created
February 26, 2014 02:08
-
-
Save jerray/9222075 to your computer and use it in GitHub Desktop.
php syntax check for git pre-receive hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
errors_buffer="" | |
working_dir="" | |
function php_syntax_check() { | |
local errors=$(php -l $file 2>&1 | grep "Parse error") | |
if [ "$errors" != "" ]; then | |
if [ "$errors_buffer" != "" ]; then | |
errors_buffer="$errors_buffer\n$errors" | |
else | |
errors_buffer="$errors" | |
fi | |
echo "Syntax errors found in file: $file " | |
fi | |
} | |
function bom_check() { | |
if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]; then | |
local errors="Found BOM in $file" | |
if [ "$errors_buffer" != "" ]; then | |
errors_buffer="$errors_buffer\n$errors" | |
else | |
errors_buffer="$errors" | |
fi | |
fi | |
} | |
function line_ending_check() { | |
grep -Hnq $'\r' "$file"; RET=$? | |
if [ $RET -ne 1 ]; then | |
errors="Windows/Mac newlines found in $file" | |
if [ "$errors_buffer" != "" ]; then | |
errors_buffer="$errors_buffer\n$errors" | |
else | |
errors_buffer="$errors" | |
fi | |
fi | |
} | |
while read old_rev new_rev ref_name | |
do | |
zero="0000000000000000000000000000000000000000" | |
if [ "$old_rev" = "$zero" ]; then | |
# Created new branch | |
list=$(git diff-tree -r ${new_rev} | awk '{if ($5 != "D") print $6}') | |
elif [ "$new_rev" = "$zero" ]; then | |
# Deleted branch | |
exit 0 | |
else | |
list=$(git diff-tree -r ${old_rev}..${new_rev} | awk '{if ($5 != "D") print $6}') | |
fi | |
#echo "DEBUG \$list: $list" | |
# if commit not contain php-files -exit | |
if [ -z "$list" ]; then | |
exit 0 | |
fi | |
working_dir="/tmp/_git_$newrev/" | |
mkdir -p $working_dir | |
echo $list |\ | |
xargs git archive --format=tar $new_rev|\ | |
(cd $working_dir && tar xf -) | |
cd $working_dir | |
for file in $list | |
do | |
echo $file | |
# Check php syntax | |
extension=$(echo "$file" | grep ".php$") | |
if [ "$extension" != "" ]; then | |
php_syntax_check $file | |
fi | |
extension=$(echo "$file" | grep -E "(java|js|php|ini|xml|yml|htm|html|tpl|sh|bat|conf|less)$") | |
if [ "$extension" != "" ]; then | |
# Check BOM | |
bom_check $file | |
# Check line endings | |
line_ending_check $file | |
fi | |
done | |
cd - > /dev/null | |
rm -rf $working_dir | |
if [ "$errors_buffer" != "" ]; then | |
echo | |
echo "These errors were found in try-to-push files: " | |
echo -e $errors_buffer | |
echo | |
echo "Can't push, please fix errors first." | |
exit 1 | |
else | |
echo "Pushed successfully." | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment