Skip to content

Instantly share code, notes, and snippets.

@proofek
Created June 2, 2011 14:21
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save proofek/1004533 to your computer and use it in GitHub Desktop.
Save proofek/1004533 to your computer and use it in GitHub Desktop.
pre-receive git hook to run php linter
#!/usr/bin/php
<?php
echo "\nRunning php linter...\n";
$params = explode(' ', file_get_contents('php://stdin'));
$ref = trim($params[1]);
$diff = array();
$return = 0;
exec("git diff --name-only $params[0] $params[1] 2> /dev/null", $diff, $return);
if ($return > 0) {
echo "Could not run git diff\n\n";
exit(1);
}
$filename_pattern = '/\.php$/';
foreach ($diff as $file) {
if (!preg_match($filename_pattern, $file)) {
continue;
}
$tree = array();
$return = 0;
exec("git ls-tree $ref $file 2> /dev/null", $tree, $return);
if ($return > 0 || empty($tree)) {
echo "Could not run git ls-tree\n\n";
exit(1);
}
$tree = preg_split('/\s/', $tree[0]);
$fileContents = array();
exec("git cat-file $tree[1] $tree[2] 2> /dev/null", $fileContents, $return);
if ($return > 0) {
echo "Could not run git cat-file\n\n";
exit(1);
}
$fileContents = implode("\n", $fileContents);
$pipes = array();
$proc = proc_open('php -l',
array(0 => array('pipe', 'r'),
1 => array('pipe', 'w')),
$pipes);
if (!is_resource($proc)) {
echo "Could not creater php linter process\n\n";
exit(1);
}
fwrite($pipes[0], $fileContents);
fclose($pipes[0]);
fclose($pipes[1]);
$resultCode = proc_close($proc);
if ($resultCode != 0) {
echo "Error parsing file '$file'\n\n";
exit($resultCode);
}
}
echo "No errors detected\n\n";
exit(0);
@madasha
Copy link

madasha commented May 16, 2016

Hello, first I'd like to thank you for the great hook - it saves me a lot of trouble :)

Just wanted to ask: Have you experienced any problems when pushing branches? I have no problems using it when pushing to master, but whenever I try to push code to branch (no matter if the code is syntactically OK or not), the hook would exit with an error status and output that "remote: Could not run git ls-tree".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment