PHP Pre-commit Hook

I am commenting the code for a pre-commit I found in php here. The idea is that we would like to embed these type of pre-commits or other type of hooks in a way that is automatized through a DevelopmentBundle as described in an earlier post here.

#!/usr/bin/php
<?php
 
// setup up variables for input output, namely an output array and resource control temporary variable
$output = array();
$rc     = 0;
// gets the sha1 for the previous to the last current commit if not the head
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $rc);
// if resource controle is found then use HEAD else use an unknown sha1
if ($rc == 0)  $against = 'HEAD';
else           $against = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
// gets the list of the files that have changed
exec('git diff-index --cached --name-only '. $against, $output);
// match expression to make sure files are php type
$needle            = '/(\.php|\.module|\.install)$/';
$exit_status = 0;
// loop over the file list
foreach ($output as $file) {
        if (!preg_match($needle, $file)) {
                // only check php files
                continue;
        }
 
        $phpcs_output = array();
        $rc              = 0;
        // calls phpcs CodeSniffer on each file
	exec('phpcs '. escapeshellarg($file), $phpcs_output, $rc);
        if ($rc == 0) {
                continue;
        }
        // outputs errors or warnings
	echo implode("\n", $phpcs_output), "\n";
        // impede the commit
        $exit_status = 1;
}

Now when doing a git commit -a phpcs will be run on the file(s) with changes:

cordoval@ms:~/sites-2/$ git commit -a
 
FILE: ...ordoval/sites-2/MyClass.php
--------------------------------------------------------------------------------
FOUND 5 ERROR(S) AFFECTING 5 LINE(S)
--------------------------------------------------------------------------------
 39 | ERROR | Multi-line function call not indented correctly; expected 8
    |       | spaces but found 12
 41 | ERROR | Multi-line function call not indented correctly; expected 8
    |       | spaces but found 12
 43 | ERROR | Multi-line function call not indented correctly; expected 8
    |       | spaces but found 12
 45 | ERROR | Multi-line function call not indented correctly; expected 8
    |       | spaces but found 12
 47 | ERROR | Multi-line function call not indented correctly; expected 8
    |       | spaces but found 12
--------------------------------------------------------------------------------
 
Time: 0 seconds, Memory: 6.75Mb

After the problems are resolved git commit -a should proceed to commit the changes.

Leave a Reply

Your email address will not be published. Required fields are marked *