Gitlab基于git-hooks做checkstyle代码检测
描述:为了规范团队代码,在成员push代码时,做代码检测规范,不符合规范的禁止成员推送代码到服务端. 基于git-hook服务器端钩子pre-receive进行处理. 关于git hooks描述请参考: Git Hooks
git-hooks基于python脚本
在gitlab安装目录下[gitlab/embedded/service/gitlab-shell/hooks]找到pre-receive文件,修改该文件加入python代码块,示例脚本如下:
#!/usr/bin/python
#coding=utf-8
import os
import sys
import subprocess
import tempfile
import shutil
__author__ = "lance"
class Trigger(object):
def __init__(self):
'''
初始化文件列表信息,提交者信息,提交时间,当前操作的分支
'''
self.pushAuthor = ""
self.pushTime = ""
self.fileList = []
self.ref = ""
def __getGitInfo(self):
'''
'''
self.oldObject, self.newObject, self.ref = sys.stdin.readline().strip().split(' ')
def __getPushInfo(self):
'''
git show命令获取push作者,时间,以及文件列表
文件的路径为相对于版本库根目录的一个相对路径
'''
rev = subprocess.Popen('git rev-list '+self.newObject,shell=True,stdout=subprocess.PIPE)
revList = rev.stdout.readlines()
revList = [x.strip() for x in revList]
#查找从上次提交self.oldObject之后还有多少次提交,即本次push提交的object列表
indexOld = revList.index(self.oldObject)
pushList = revList[:indexOld]
pushList.reverse()
# temp file
tempdir = tempfile.mkdtemp('git_hook')
#循环获取每次提交的文件列表
for pObject in pushList:
p = subprocess.Popen('git show '+pObject,shell=True,stdout=subprocess.PIPE)
pipe = p.stdout.readlines()
pipe = [x.strip() for x in pipe]
#print("===>",pipe)
#验证是否java文件
file = pipe[6].strip("diff").strip()
if not file.lower().endswith('.java'):
continue
filename = file.split('/')[-1]
#git get Tree
content_hash = pipe[7].strip("index").strip()[9:16]
content_p = subprocess.Popen('git cat-file -p '+content_hash,shell=True,stdout=subprocess.PIPE)
cpipe = content_p.stdout.readlines()
#print(cpipe)
with open(os.path.join(tempdir, filename), 'w+') as fp:
fp.writelines(cpipe)
#self.handler_checkstyle(tempdir+"/"+content_hash+'.java')
# checkstyle
self.handler_checkstyle(tempdir)
def getGitPushInfo(self):
self.__getGitInfo()
self.__getPushInfo()
if __name__ == "__main__":
#print("argv: ", sys.argv)
t = Trigger()
t.getGitPushInfo()
exit(0)
通过获取git推送信息,并保存到临时目录文件下
通过checkstyle命令行模式检测代码是否符合配置的规则
通过java -jar启动checkstyle做代码检测, 并把不符合规范代码提示打印给客户端, 供客户端进行检测修改, 并再次进行代码推送. 代码规则定义google_checks.xml采用Google定义的检测规范, 可以做适当的修改
# 处理java文件
def handler_checkstyle(self, file):
try:
cmd = r'java -jar /mnt/checkstyle-8.11-all.jar -c /mnt/google_checks.xml '+file+'/'
#print(cmd)
result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
rpipe = result.stdout.readlines()
if len(rpipe)>2:
print(rpipe)
exit(1)
finally:
shutil.rmtree(file)
#pass