GIT服务器钩子设置

2019-11-11  本文已影响0人  jayswu

项目越来越大,人员越来越多,代码变动很难通知到每一个项目组成员,尤其是一些核心配置的变动,故此需要在GIT代码库服务端做控制,客户端也可以,但是需要每一个人都在本地进行配置,麻烦亦没必要

核心诉求:

1、限制成员提交代码注释长度

2、核心配置文件修改需要邮件通知到每一个开发人员

要解决第一个诉求用到了GIT的pre-receive钩子,这个钩子会在客户端发起push请求后调用执行,只有执行通过才能合并进代码库,话不多说直接上代码:


#!/bin/bash

#pre-receive script

#set -x #for debugging

validate_ref()

{

    # --- Arguments

    oldrev=$(git rev-parse $1)

    newrev=$(git rev-parse $2)

    refname="$3"

    commitList=`git rev-list $oldrev..$newrev`

        #echo $commitList

    split=($commitList)

    for s in ${split[@]}

    do

        echo "@@@@@@@"

        echo "$s"

        msg=`git cat-file commit $s | sed '1,/^$/d'`

        echo $msg

        if [ ${#msg} -lt 15 ];then

            echo "!!! Commit message length less than 15"

            exit 1

        else

            echo "bigger than 5"

        fi

    done

}

fail=""

# Allow dual mode: run from the command line just like the update hook, or

# if no arguments are given then run as a hook script

if [ -n "$1" -a -n "$2" -a -n "$3" ]; then

    # Output to the terminal in command line mode - if someone wanted to

    # resend an email; they could redirect the output to sendmail

    # themselves

    PAGER= validate_ref $2 $3 $1

else

    while read oldrev newrev refname

    do

        validate_ref $oldrev $newrev $refname

    done

fi

if [ -n "$fail" ]; then

    exit $fail

fi

将代码文件命名为pre-receive,并且可执行权限设置为777(注意跨平台文件格式问题)
在git服务器源代码存储的目录(如abc.git),在abc.git目录创建一个新目录custom_hooks
将pre-receive放在custom_hooks目录下,不用重启gitlab会立刻生效。

第二个诉求的实现要稍微复杂一些,因为涉及到发送邮件,需要外挂一个python脚本实现,这里用到了git的另一个钩子post_receive,这个钩子会在代码入库后执行,文件内容很简单:

#!/bin/sh
#一定要编写这句话,清除GIT自己设置的根目录,否则无法正常执行下一句
#经过实际测试,可能不需要此行,大家看自己情况加
#unset GIT_DIR

#用python2执行py文件,就是cmd命令,需要指定py文件的绝对路径,python3需要多加一行,具体看代码
python /data/hooks/send.py

下面是send.py的代码:

# coding:utf-8
import smtplib as sm
from email.mime.text import MIMEText
from subprocess import check_output

#发送邮箱的smtp服务器
mail_host = 'smtpdm.aliyun.com'
#发送邮箱
sender = '77777777@qq.com'
#发送邮箱的smtp的授权码(非邮箱的登录密码)
password = '12345678'
#接收者邮箱
receiver = '8888@qq.com,9999@qq.com'
#邮箱主题
subject = 'Code Update Notification'

#需要邮件提醒的文件
file1 = 'src/main/webapp/WEB-INF/web.xml'
file2 = 'src/main/resources/'

def Info():
    '''
    该函数主要用来获取最近一次更新记录,并提取主要信息:
    '''
    #使用subprocess的check_output函数来捕获git命令后的
    #标准输出,以获取最近一次更新记录,该记录是一个字符串
    #log = check_output(['git','log','-l','-p'])
    log = check_output(['git','show','--stat'])
    #规避TypeError: a bytes-like object is required, not 'str',byte转str
    log = str(log,encoding="utf-8")

    #print(files)
    if (file1 in log) or (file2 in log):
        detail = log.split('\n\n')
        #对字符串进行分割,以获取相关信息author date comment
        #更新者
        #print(detail)
        updater = detail[0].split('\n')[1].replace('Author','Updater')
        #print(updater)
        #更新时间,去掉最后的更新次数信息
        update_time = detail[0].split('\n')[-1].replace('Date','Update time')[0:-6]
        #注释,并去掉左右两边空格
        try:
            comment = 'Comment: '+detail[1].strip()
        except:
            comment = 'Comment: '+"Sorry,the updater didn't comment."
        #影响文件
        files = 'Files:<br>'+detail[2].replace('\n','<br>')
        #要比对文件需拿到第一步骤中的commitId使用git show commitId命令获取
        msg = """
            <h3 style='color:red'>Hi,buddy!</h3>
            <h3 style='color:red;text-indent:2em'>The resource file has been updated,the following is details:</h3>
            <h3 style='color:red;text-indent:4em'>{0}</h3>
            <h3 style='color:red;text-indent:4em'>{1}</h3>
            <h3 style='color:red;text-indent:4em'>{2}</h3>
            <h3 style='color:red;text-indent:4em'>{3}</h3>
            <h3 style='color:red;text-indent:2em'>If any question,please contact the updater</h3>
            """.format(updater,update_time,comment,files) 
    
        msg = MIMEText(msg,'html','utf-8')

        send_email(msg)

def send_email(msg):
    '''
    发送邮件
    '''
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject

    smtpObj = sm.SMTP(mail_host)
    smtpObj.login(sender,password)
    smtpObj.sendmail(sender,receiver.split(','),msg.as_string())
    smtpObj.quit()

if __name__ =='__main__':
    Info()

是不是很简单!看完记得点赞哦

上一篇下一篇

猜你喜欢

热点阅读