Skip to content

Instantly share code, notes, and snippets.

@chales
Created January 15, 2015 15:40
Show Gist options
  • Save chales/7665555e32430ef4035b to your computer and use it in GitHub Desktop.
Save chales/7665555e32430ef4035b to your computer and use it in GitHub Desktop.
Git pre-commit hook to run PHP Lint and PHP_CodeSniffer against Drupal project commits.
#!/usr/bin/php
<?php
/**
* @file
* Git pre-commit hook that runs PHP lint and PHPCS against commits.
* DrupalCS requires PHPCS 1.x
*
* Install:
* 1. Copy this file to /<my/git/project>/.git/hooks/pre-commit
* 2. Make executable (chmod a+x pre-commit)
*/
$exit_code = 0;
$return = 0;
$files = array();
$phpcs = trim(shell_exec('which phpcs'));
// Get GIT revison.
exec('git rev-parse --verify HEAD 2> /dev/null', $files, $return);
$compare = ($return == 0) ? 'HEAD' : '';
// Build files array.
exec("git diff-index --cached --name-only {$compare}", $files);
print "\nExamine Files\n\n";
// Review the committed files.
foreach ($files as $file) {
// File extensions to test.
$file_extensions = array(
'engine',
'inc',
'install',
'engine',
'module',
'php',
'profile',
'test',
'theme',
'txt',
);
// Only check specified extensions
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array($ext, $file_extensions)) {
continue;
}
if (file_exists($file) && !is_dir($file)) {
$file = escapeshellarg($file);
echo "\n\033[1;31mExamining: {$file}\033[0m\n";
$dir = str_replace('\'', '', dirname($file));
$extra = '';
if ($dir !== '.') {
$extra = $dir . '/';
}
$output = array();
// PHP code sniffer check.
$return_phpcs = 0;
$filename = str_replace('\'', '', basename($file));
$file_extensions = implode($file_extensions, ',');
$path = __DIR__ . '/../../' . $extra;
$phpcs_cmd = "cd {$path} && {$phpcs} --standard=Drupal --extensions="
. "'{$file_extensions}' {$filename}";
exec($phpcs_cmd, $output, $return_phpcs);
// PHP lint check.
$return_lint = 0;
$lint_output = array();
$lint_cmd = "php -l {$file}";
exec($lint_cmd, $lint_output, $return_lint);
if (($return_phpcs !== 0) || ($return_lint !== 0)) {
echo implode("\n", $output), "\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