Skip to content

Instantly share code, notes, and snippets.

@paunin
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paunin/6029c4b6248450dc06df to your computer and use it in GitHub Desktop.
Save paunin/6029c4b6248450dc06df to your computer and use it in GitHub Desktop.
pre-commit Code Sniffer
#!/usr/bin/php
<?php
$cs = 'phpcs';
$md = 'phpmd';
$output = [];
$return = 0;
$defaultCsStandard = 'PSR2';
$defaultMdRules = 'codesize,cleancode,controversial,unusedcode,naming,design';
$gitRoot = exec('git rev-parse --show-toplevel', $output);
$csRuleSet = $gitRoot . '/lint/phpcs/ruleset.xml';
$mdRuleSet = $gitRoot . '/lint/phpmd/ruleset.xml';
$csStandard = file_exists($csRuleSet) ? $csRuleSet : $defaultCsStandard;
$mdRules = file_exists($mdRuleSet) ? $mdRuleSet : $defaultMdRules;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
// Get GIT revision
$against = $return === 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
// Get the list of files in this commit.
exec($commandDiff = "git diff-index --name-only {$against}", $output);
$filename_pattern = '/(\.php|\.phtml)$/';
$exitStatus = 0;
// Loop through files.
foreach ($output as $file) {
echo "Validating $file\n";
if (!preg_match($filename_pattern, $file)) {
continue; // don't check files that aren't PHP
}
if (!file_exists($file)) {
continue; // If file is removed from git do not sniff.
}
$csOutput = [];
// Run the sniff
exec("$cs --standard=$csStandard " . escapeshellarg($file), $csOutput, $return);
if ($return !== 0) {
echo implode("\n", $csOutput), "\n";
$exitStatus = 1;
}
// Run PHPMD
exec("$md " . escapeshellarg($file) . " text $mdRules", $mdOutput, $return);
if ($return !== 0) {
echo implode("\n", $mdOutput), "\n";
$exitStatus = 1;
}
}
exit($exitStatus);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment