8

I'd like to check code committed to my remote git repository with PHP CodeSniffer and reject it if there are any problems code standards. Does anyone have an example how to use it on git remote repository or maybe example how to use it with pre-receive hook? Thanks.

hakre
  • 193,403
  • 52
  • 435
  • 836
rzajac
  • 1,591
  • 2
  • 18
  • 37

4 Answers4

3

Maybe this point you in the right direction: (Orginal from: http://www.squatlabs.de/versionierung/arbeiten-git-hooks in German)

#!/usr/bin/php
<?php

$output = array();
$rc     = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $rc);
if ($rc == 0)  $against = 'HEAD';
else           $against = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';

exec('git diff-index --cached --name-only '. $against, $output);

$needle            = '/(\.php|\.module|\.install)$/';
$exit_status = 0;

foreach ($output as $file) {
        if (!preg_match($needle, $file)) {
                // only check php files
                continue;
        }

        $lint_output = array();
        $rc              = 0;
        exec('php -l '. escapeshellarg($file), $lint_output, $rc);
        if ($rc == 0) {
                continue;
        }
        # echo implode("\n", $lint_output), "\n";
        $exit_status = 1;
}

exit($exit_status);

You will have to edit the exec line exec('php -l... to point to your codesniffer installation.

Rufinus
  • 29,200
  • 6
  • 68
  • 84
  • unfortunately it does not work with pre-receive hook :( – rzajac Mar 29 '10 at 18:47
  • Nop, you'll have to create a pre-commit on client side, but you can track the hook so each developpers will have to pull the hooks. AFAIK, you the server can't test the content when pushing... :( – FMaz008 Nov 07 '11 at 16:31
3

Ok I found the solution :)

This is proof of concept code :) for pre-receive hook:

#!/bin/bash

while read old_sha1 new_sha1 refname; do
    echo "ns: " $new_sha1;
    echo "os: " $old_sha1;

    echo "----"

    git ls-tree -r $new_sha1 | cut -f 3 -d ' ' | cut -f 1 | while read file; do
        git cat-file blob $file
    done; 

    echo "----"

done

exit 1

This example code will only print blobs received by remote repository but it's enough to get someone needing something like that going (I hope).

You can put every blob in some temporary file run whatever you need on this file delete the file and so on...

rzajac
  • 1,591
  • 2
  • 18
  • 37
2

I developed a pre-receive git hook based on PHPCodeSniffer to check the code styling of PHP, JavaScript and CSS files.

My script is available from Github : https://github.com/blueicefield/PHP_CodeSniffer_GIT_Hook

Blueicefield
  • 5,269
  • 1
  • 16
  • 8
  • Can you extend your answer with an example? Like the bash example in an answer above? So it's clear from the answer alone how to use? – hakre Jun 10 '12 at 15:04
2

This might help: http://github.com/s0enke/git-hooks/tree/master/phpcs-pre-commit/

s0enke
  • 21
  • 1