0

Gitlab 配置自定义Git Hooks,检查PHP语法错误

jk created at5 years ago view count: 2722

首先查考Gitlab官方的Hook配置

https://docs.gitlab.com/ee/administration/custom_hooks.html

配置<project>.git/custom_hooks/pre-receive

pre-receive的内容如下

#!/usr/bin/php
<?php

echo "\nRunning php linter...\n";

$params = explode(' ', file_get_contents('php://stdin'));
$ref = trim($params[1]);

$diff = array();
$return = 0;

exec("git diff --name-only $params[0] $params[1] 2> /dev/null", $diff, $return);

if ($return > 0) {

  echo "Could not run git diff\n\n";
  // exit(1);
}

$filename_pattern = '/\.php$/';

foreach ($diff as $file) {

    if (!preg_match($filename_pattern, $file)) {

        continue;
    }

    $tree = array();
    $return = 0;

    exec("git ls-tree $ref $file 2> /dev/null", $tree, $return);
    if ($return > 0 || empty($tree)) {

        echo "Could not run git ls-tree\n\n";
        exit(1);
    }
    $tree = preg_split('/\s/', $tree[0]);

    $fileContents = array();
    exec("git cat-file $tree[1] $tree[2]  2> /dev/null", $fileContents, $return);
    if ($return > 0) {

        echo "Could not run git cat-file\n\n";
        exit(1);
    }

    $fileContents = implode("\n", $fileContents);

    $pipes = array();
    $proc = proc_open('php -l',
                  array(0 => array('pipe', 'r'),
                        1 => array('pipe', 'w')),
                $pipes);

    if (!is_resource($proc)) {

        echo "Could not creater php linter process\n\n";
        exit(1);
    }

    fwrite($pipes[0], $fileContents);
    fclose($pipes[0]);
    fclose($pipes[1]);
    $resultCode = proc_close($proc);

    if ($resultCode != 0) {

        echo "Error parsing file '$file'\n\n";
        exit($resultCode);
    }
}

echo "No errors detected\n\n";
exit(0);
report
回复
1

一般我都是本地配置

5 years ago 回复

相关搜索关键词