Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Created February 4, 2009 11:58
Show Gist options
  • Save hugowetterberg/58067 to your computer and use it in GitHub Desktop.
Save hugowetterberg/58067 to your computer and use it in GitHub Desktop.
Git pre commit hook written in php that validates the syntax of php files and removes trailing whitespace before commit
{
s/[[:space:]]*$//
s/\$Id: .* Exp \$/$Id$/g
}
#!/opt/local/bin/php
<?php
$output = array();
$return = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
$against = $return == 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
exec("git diff-index --cached --name-only {$against}", $output);
$php_pattern = '/(\.(php)|(inc)|(install)|(module))$/';
$cleanup_pattern = '/(\.(css)|(js)|(info)|(txt))$/';
$exit_status = 0;
foreach ($output as $file) {
if (!file_exists($file)) {
continue;
}
$is_php = preg_match($php_pattern, $file);
$may_cleanup = $is_php || preg_match($cleanup_pattern, $file);
if ($may_cleanup) {
// Perform some cleanup
exec(sprintf('sed -f ".git/hooks/cleanup.sed" -ie "%s"', $file, $file));
unlink($file . 'e');
exec(sprintf('git add "%s"', $file));
}
if ($is_php) {
$preg = '/^PHP Parse error:\s+(.+)\s+in\s+(.+)\s+on line\s+(\d+)$/';
// Check php syntax
$lint_output = array();
exec("php -l " . escapeshellarg($file) . ' 2>&1', $lint_output, $return);
if ($return) {
foreach ($lint_output as $line) {
$match = array();
if (preg_match($preg, $line, $match)) {
echo "# PHP Parse error:\n# {$match[1]}\n# File: {$match[2]}\n# Line: {$match[3]}\n";
}
else {
echo "# {$line}\n";
}
}
$exit_status = 1;
}
}
}
exit($exit_status);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment