当前位置: 首页 > 工具软件 > Git.php > 使用案例 >

PHP代码Git提交前添加 phpcs 语法检查

厉文栋
2023-12-01

1.安装phpcs

sudo apt install php-codesniffer

设置标准

phpcs --config-set default_standard PSR2

设置编码

phpcs --config-set encoding utf-8

2.git集成提交前代码检查

打开当前项目的.git/hooks目录,里面有很多xxx.sample文件, 其中一个就是pre-commit.sample。

cp pre-commit.sample pre-commit && vim pre-commit

修改pre-commit文件,将下面代码替换掉里面的原来的代码

#!/bin/bash
#
# check PHP code syntax error and standard with phpcs
 
PROJECT=$(git rev-parse --show-toplevel) 
cd $PROJECT 
SFILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\.php) 
TMP_DIR=$PROJECT."/tmp" 
 
 
# Determine if a file list is passed
if [ "$#" -ne 0 ] 
then 
    exit 0 
fi 
 
echo "Checking PHP Lint..." 
 
for FILE in $SFILES 
do
# echo "php -l -d display_errors=0 ${FILE}"
# echo "git show :$FILE > $TMP_DIR/$FILE"
    php -l -d display_errors=0 $FILE 
    if [ $? != 0 ] 
    then 
        echo "Fix the error before commit." 
        exit 1 
    fi 
    FILES="$FILES $PROJECT/$FILE" 
done 
 
if [ "$FILES" != "" ] 
then 
    echo "Running Code Sniffer..." 
    
    TMP_DIR=/tmp/$(uuidgen) 
    mkdir -p $TMP_DIR 
    for FILE in $SFILES 
    do 
        mkdir -p $TMP_DIR/$(dirname $FILE) 
        git show :$FILE > $TMP_DIR/$FILE 
    done 
    phpcs --standard=PSR2 --encoding=utf-8 -n $TMP_DIR 
    PHPCS_ERROR=$? 
    rm -rf $TMP_DIR 
    if [ $PHPCS_ERROR != 0 ] 
    then 
        echo "Fix the error before commit." 
        exit 1 
    fi 
fi 
 
exit $?

 
 

 

 
 
 

 

 类似资料: