Skip to content

Instantly share code, notes, and snippets.

@cmcintosh
Forked from jpoesen/pre-commit
Last active August 29, 2015 14:07
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 cmcintosh/0cf2481c24fd85ee2252 to your computer and use it in GitHub Desktop.
Save cmcintosh/0cf2481c24fd85ee2252 to your computer and use it in GitHub Desktop.
#!/usr/bin/php
<?php
/**
* @file
* A Git pre-commit hook script to check files for PHP syntax errors and Drupal
* coding standards violations. Requires phpcs and Coder Sniffer:
*
* @see https://drupal.org/node/1419988
* Hat tip: dcq.module (DrupalCodeQuality)
*
* Usage:
* 1. Put this file in /yourproject/.git/hooks/
* 2. Ensure this file is executable (chmod a+x pre-commit)
* 3. Commit code
*/
// 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);
print "\nPrecommit\n\n";
foreach ($files as $file) {
if (file_exists($file) && !is_dir($file)) {
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);
$dir = str_replace('\'', '', dirname($file));
$extra = '';
if ($dir !== '.') {
$extra = $dir . '/';
}
// Run PHP lint check.
$return = 0;
$lint_cmd = "php -l {$file}";
$lint_output = array();
exec($lint_cmd, $lint_output, $return);
if ($return !== 0) {
// Set exit code.
$exit_code = 1;
}
// Get file name for checking.
$filename = str_replace('\'', '', basename($file));
// Run phpcs.
$return = 0;
$file_extensions = implode($file_exts, ',');
$phpcs_cmd = 'cd ' . __DIR__ . '/' . $return_back . $extra
. ' && phpcs --standard=drupal --extensions='
. $file_extensions . ' ' . $filename;
exec($phpcs_cmd, $phpcs_output, $return);
if ($return !== 0) {
// Show output 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