Skip to content

Instantly share code, notes, and snippets.

@paolomainardi
Created September 26, 2014 00:20
Show Gist options
  • Save paolomainardi/50f8df0cbca7f13aba9e to your computer and use it in GitHub Desktop.
Save paolomainardi/50f8df0cbca7f13aba9e to your computer and use it in GitHub Desktop.
#!/usr/bin/php
<?php
/**
* @file
* A Git pre-commit hook script to run phpmd.
*/
$return_back = '../../';
$php_md_bin = realpath(getcwd() . '/bin/phpmd');
// Building an array of ignored files and folders.
$file_path = __DIR__ . '/' . $return_back . '.dcq_ignore';
$ignore = array();
if (file_exists($file_path)) {
$file = fopen($file_path, "r");
if ($file) {
while (!feof($file)) {
$ignore[] = fgets($file);
}
}
}
// Extensions of files to test.
$file_exts = array(
'engine',
'php',
'module',
'inc',
'install',
'profile',
'test',
'theme',
'txt',
);
$exit_code = 0;
$files = array();
$return = 0;
// Determine whether this is the first commit or not. If it is, set $against to
// the hash of a magical, empty commit to compare to.
exec('git rev-parse --verify HEAD 2> /dev/null', $files, $return);
$against = ($return == 0) ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
// Identify changed files.
exec("git diff-index --cached --name-only $against", $files);
// The number of ignored items.
$ignored_items_count = count($ignore);
echo "\033[1;33mPHP Mess detector - pre-commit hook\033[0m\n\n";
foreach ($files as $file) {
if (file_exists($file) && !is_dir($file)) {
// Check files to ignore.
if ($ignored_items_count > 0) {
foreach ($ignore as $key => $value) {
if (substr($file, 0, strlen(trim($value))) == trim($value) && trim($value) != '') {
echo "\033[0;31mIgnored by DCQ - $file\n\033[0m";
continue 2;
}
}
}
echo "\033[0;32mChecking file {$file}\033[0m\n\n";
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array($ext, $file_exts)) {
continue;
}
$phpcs_output = array();
$file = escapeshellarg($file);
// Add extra path to get warranty for run drush.
$dir = str_replace('\'', '', dirname($file));
$extra = '';
if ($dir !== '.') {
$extra = $dir . '/';
}
// Get file name for checking.
$filename = str_replace('\'', '', basename($file));
// Perform phpcs test.
$return = 0;
$phpmd_cmd = 'cd ' . __DIR__ . '/' . $return_back . $extra . ' && ' . $php_md_bin . " {$filename} text unusedcode";
exec($phpmd_cmd, $phpcs_output, $return);
if ($return !== 0) {
// Format error messages and set exit code.
echo implode("\n", $phpcs_output), "\n";
$exit_code = 1;
}
}
}
exit($exit_code);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment