互联网上的文章真TM不靠谱 还是自己来的好 --只写靠谱的文档

gitlab pre-commit钩子实现代码质量静态分析

gitlab支持像svn的服务端钩子一样添加钩子

具体文档在 https://docs.gitlab.com/ce/administration/custom_hooks.html

一般来说 钩子的路径 在 /var/opt/gitlab/git-data/repositories/\<group\>/\<project\>.git

支持最多的是pre-receive

使用pphpcs检测

 #! /usr/bin/env python2.7
# coding=utf-8

import sys, subprocess, os, commands, simplejson


class Trigger(object):
    def __init__(self):
        self.fileList = []
        self.ref = ""
        self.phpcsbin = '/usr/local/php7.0/bin/phpcs'
        self.tmpdir = '/tmp/svnhooktmpfile/'

    def __getGitInfo(self):
        self.oldObject, self.newObject, self.ref = sys.stdin.readline().strip().split(' ')

    def __getPushInfo(self):
        tmp = commands.getoutput('git rev-list ' + self.oldObject + '..' + self.newObject)
        pushlist = tmp.split('\n')
        # 循环获取每次提交的文件列表
        for pObject in pushlist:
            s = commands.getoutput('git show --pretty="format:" --name-only ' + pObject)
            filelisttmp = s.split('\n')
            for s in filelisttmp:
                if s not in self.fileList:
                    self.fileList.insert(0, s)
        is_exit = 0
        for path in self.fileList:
            name, ext = os.path.splitext(path)
            if ext == '.php':
                tmp_file = self.tmpdir + self.newObject
                commands.getoutput('git show ' + self.newObject + ':' + path + ' > ' + tmp_file)
                phpcs_result = commands.getoutput(
                    self.phpcsbin + ' --report=json -n -s --standard=PEAR ' + tmp_file);
                os.remove(tmp_file)
                phpcs_result = simplejson.loads(phpcs_result)
                if phpcs_result['totals']['errors'] > 0:
                    is_exit = 1
                    print '文件:' + path
                    for s1 in phpcs_result['files']:
                        s2 = phpcs_result['files'][s1]['messages']
                        for s3 in s2:
                            print '第' + str(s3['line']) + '行:' + s3['message'].encode('utf-8')
        exit(is_exit)

    def getGitPushInfo(self):
        self.__getGitInfo()
        self.__getPushInfo()
        exit(1)


if __name__ == "__main__":
    t = Trigger()
    t.getGitPushInfo()

标签: none

添加新评论