有没有更好的方法编写 git 预提交挂钩来检查提交中的任何 php 文件是否有解析错误?
-
09-06-2019 - |
题
到目前为止我所拥有的是
#!/bin/sh
php_syntax_check()
{
retval=0
for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
if [ -f $i ]; then
output=$(php -l $i)
retval=$?
if [ $retval -gt 0 ]; then
echo "=============================================================================="
echo "Unstaging $i for the commit due to the follow parse errors"
echo "$output"
git reset -q HEAD $i
fi
fi
done
if [ $retval -gt 0 ]; then
exit $retval
fi
}
php_syntax_check
解决方案
如果提交是部分提交(并非工作树中的所有更改都已提交),则此 make 会给出不正确的结果,因为它测试的是工作副本而不是暂存副本。
一种方法可以是:
git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
find $TMPDIR -name '*.php' -print | xargs -n 1 php -l
这会将暂存图像的副本复制到暂存空间,然后在那里对其运行测试命令。如果任何文件在构建中包含其他文件,那么您可能必须在测试树中重新创建整个暂存映像,然后在那里测试更改的文件(请参阅: Git 预提交挂钩:更改/添加文件).
其他提示
如果这是题外话,我很抱歉,但是您不应该在提交之前运行某种自动化测试(这意味着代码没有语法错误)吗?
如果您安装了 php5-cli,您可以用 PHP 编写预提交并使用您更熟悉的语法。
只是做一些更像的事情。
#!/usr/bin/php
<?php /* Your pre-commit check. */ ?>
我的预提交挂钩的 PHP 实现使用“php-code-sniffer”或“php-cs-fixer”检查 git 中修改的文件是否“无错误”并且符合 PSR2 标准
#!/usr/local/bin/php
<?php
/**
* Collect all files which have been added, copied or
* modified and store them in an array - output
*/
exec('git diff --cached --name-only --diff-filter=ACM', $output);
$isViolated = 0;
$violatedFiles = array();
// $php_cs_path = "/usr/local/bin/php-cs-fixer";
$php_cs_path = "~/.composer/vendor/bin/phpcs";
foreach ($output as $fileName) {
// Consider only PHP file for processing
if (pathinfo($fileName, PATHINFO_EXTENSION) == "php") {
$psr_output = array();
// Put the changes to be made in $psr_output, if not as per PSR2 standard
// php-cs-fixer
// exec("{$php_cs_path} fix {$fileName} --rules=@PSR2 --dry-run --diff", $psr_output, $return);
// php-code-sniffer
exec("{$php_cs_path} --standard=PSR2 --colors -n {$fileName}", $psr_output, $return);
if ($return != 0) {
$isViolated = 1;
$violatedFiles[] = $fileName;
echo implode("\n", $psr_output), "\n";
}
}
}
if ($isViolated == 1) {
echo "\n---------------------------- IMPORTANT --------------------------------\n";
echo "\nPlease use the suggestions above to fix the code in the following file: \n";
echo " => " . implode("\n => ", $violatedFiles);
echo "\n-----------------------------------------------------------------------\n\n\n";
exit(1);
} else {
echo "\n => Committed Successfully :-)\n\n";
exit(0);
}
不隶属于 StackOverflow