Created
February 9, 2016 14:57
-
-
Save yitsushi/8ba8b5be068cf452c98b to your computer and use it in GitHub Desktop.
"php -l" before commit
This file contains hidden or 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
#!/usr/bin/env php | |
<?php | |
$files = array(); | |
$returnValue = 0; | |
$exitStatus = 0; | |
$acceptedExtensions = array('php'); | |
# git revision | |
exec('git rev-parse --verify HEAD 2> /dev/null', $files, $returnValue); | |
$compare = ($returnValue == 0) ? 'HEAD' : ''; | |
# changed files | |
exec("git diff-index --cached --name-only {$compare}", $files); | |
foreach($files as $file) { | |
if (!file_exists($file) || is_dir($file)) { | |
continue; | |
} | |
$ext = pathinfo($file, PATHINFO_EXTENSION); | |
if (!in_array($ext, $acceptedExtensions)) { | |
continue; | |
} | |
echo "Check {$file}..."; | |
$file = escapeshellarg($file); | |
$dir = str_replace('\'', '', dirname($file)); | |
$extra = ''; | |
if ($dir !== '.') { | |
$extra = $dir . '/'; | |
} | |
$lintCmd = "php -l {$file}"; | |
$pipes = array(); | |
$descriptorspec = array( | |
0 => array("pipe", "r"), // stdin | |
1 => array("pipe", "w"), // stdout | |
2 => array("pipe", "w"), // stderr | |
); | |
$process = proc_open($lintCmd, $descriptorspec, $pipes); | |
$stdout = stream_get_contents($pipes[1]); | |
$stderr = stream_get_contents($pipes[2]); | |
if (strlen($stderr) < 1) { | |
echo "ok", PHP_EOL; | |
continue; | |
} | |
echo "failed", PHP_EOL; | |
if (preg_match('/on line ([0-9]+)/', $stderr, $matches)) { | |
$exitStatus = 1; | |
if (isset($matches[1])) { | |
$output = ""; | |
$before = max($matches[1] - 2, 0); | |
$after = $matches[1] + 2; | |
exec("cat -n {$file} | sed -n {$before},${after}p", $output, $returnValue); | |
echo "--- FAILED -----------", PHP_EOL; | |
echo implode(PHP_EOL, $output), PHP_EOL; | |
echo "----------------------", PHP_EOL; | |
} else { | |
echo $stderr; | |
} | |
} | |
} | |
if ($exitStatus > 0) { | |
echo PHP_EOL, "PHP errors detected... Fix it before commit"; | |
} | |
exit($exitStatus); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment