git php 代码检查,gitlab下对php代码进行检测

我们都知道,有一个世界上最好的语言。

但在实际项目中也要考虑下历史的进程,避免一些错误导致程序无法运行,比如语法上的错误,所以我们要对代码进行检测。实现这个目标需要解决几个问题:

什么时候检测代码,并拒绝异常代码的提交

以什么做标准

通过什么工具来检测

什么时候检测

gitlab的hook默认有三个:post-receive pre-receive update

其中: post-receive用于代码提交完成后的操作,比如完成提交后对代码进行发布,或者做些通知

pre-receive 用于代码提交时,通过它可以对代码进行检测,如果有异常时,可以阻止代码提交

update与pre-receive类似,但它可以对多个分支进行检测。

这次使用pre-receive。更多关于它们的内容参考:

https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

以什么做标准

这次使用phplint,详细参考

https://github.com/overtrue/phplint/blob/master/README.md

部署步骤如下:

1.gitlab服务器上需要有对应的php版本,composer,以Ubuntu为例

安装php5.6

sudo apt-get purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`

sudo add-apt-repository ppa:ondrej/php

sudo apt-get update

sudo apt-get install php5.6

sudo apt-get install php5.6-mbstring php5.6-mcrypt php5.6-mysql php5.6-xml

安装composer

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

2.通过composer安装phplint

切换到git用户安装

su git

composer require overtrue/phplint -vvv

通过什么工具来检测

git的hook支持任意的可执行的语言,php,python,ruby,perl,shell等都可以。这次以python为例

1.进入到相应项目的仓库下,默认hooks是个软连接,把它删除,重新建个hooks,注意,不要直接进去删除原来的hook

rm hooks

mkdir hooks

chown git:git hooks

建个临时文件夹

mkdir /tmp/gits

chmod 777 /tmp/gits

2.添加pre-receive,内容如下,注意需要给它执行权限

#!/usr/bin/env python

#coding:utf8

import re

import os

import sys

import fileinput

import subprocess

def checkphp(filename):

files = '/tmp/hooks/%s' % filename

cmd = '/home/git/vendor/bin/phplint %s' % files

p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

status = p.wait()

result = p.stdout.read().split('\n\n')[-1]

info = re.sub("/tmp/hooks/","", result)

return status,info

def main():

tmp = []

for line in fileinput.input():

tmp.append(line.strip('\n'))

data = tmp[0].split()

old = data[0]

new = data[1]

state = 0

staged_cmd = 'git diff --name-status %s %s' % (old,new)

proc = subprocess.Popen(staged_cmd, shell=True, stdout=subprocess.PIPE)

with proc.stdout as std_out:

for staged in std_out.readlines():

staged = staged.split()

staged_file = staged[1]

tag = staged[0]

directory = os.path.dirname('/tmp/hooks/%s' % staged_file)

if not os.path.exists(directory):

os.makedirs(directory)

if tag != 'D' and re.match('.*.php', staged_file):

content = os.popen('git show %s:%s' % (new,staged_file)).read()

openfile = open('/tmp/hooks/%s' % staged_file, 'w')

openfile.write(content)

openfile.close()

status,info = checkphp(staged_file)

if status == 1:

print '=================== error ======================='

print info

state = 1

sys.exit(state)

if __name__ == '__main__':

main()

以上步骤完成后,就可以对php进行语法检测了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值