#!/usr/bin/python
# Author Roman Nowicki (http://nowicki.cjb.net)
# A server-side git hook script for checking PHP syntax and validating coding standard
# Depends on: PHP_CodeSniffer (http://pear.php.net/package/PHP_CodeSniffer/)
# Install: copy this script to <server side repo location>/hooks/pre-receive
#!/usr/bin/python
# Author Roman Nowicki

import os
import sys
oldrev, newrev, ref = sys.stdin.read().strip().split(' ')
test_file = os.popen('mktemp').read().strip()
coding_standards = '/home/gitosis/coding_standards.xml'
for line in os.popen('git diff --name-only %s %s' % (oldrev, newrev)).readlines():
    extension = line.split('.')[-1].strip()
    file_name = line.strip()

    if(extension == 'php'):
        os.system("git cat-file -p %s:%s > %s" % (newrev, file_name, test_file))
        if 0 != os.system('php -l ' + test_file + ' > /dev/null'):
            print "PHP Syntax error in file %s" % (file_name)
            sys.exit(1)

        if 0 != os.system("phpcs -n --standard=%s %s" % (coding_standards, test_file)):
            print "Coding standards fail in file %s" % (file_name)
            sys.exit(2)
