Git-Hook介绍

Travis 于 2021-01-28 发布

目录

Git hook

两种 hook 方式

客户端 hook

每个本地初始化的 git 目录都包含一个 hook 的样例文件夹
要想使用这些样例 hook ,去掉后缀 sample

1. 提交工作流

pre-commit
在键入提交信息前运行。用于检查即将提交的快照。
使用 git commit –no-verify 来绕过这个环节

prepare-commit-msg
在启动提交信息编辑器之前,默认信息被创建之后运行。
它允许你编辑提交者所看到的默认信息。
可以结合提交模板来使用它,动态地插入信息。

commit-msg
钩子接收一个参数,存有当前提交信息的临时文件的路径。
如果该钩子脚本以非零值退出,Git 将放弃提交。

post-commit
钩子在整个提交过程完成后运行。
该钩子一般用于通知之类的事情。
可以使用 git log -l HEAD 来获取最后一次的提交信息。

2. 电子邮件工作流钩子

3. 其它客户端钩子

服务器端 hook

pre-receive
处理来自客户端的推送操作时,最先被调用的脚本是 pre-receive。
如果脚本非零值退出,所有的推送内容都不会被接受。

update
为每一个准备更新的分支各运行一次。

post-receive
在整个过程完结以后运行,可以用来更新其他系统服务或者通知用户。

业务场景

使用 serverhook 的 post-receive 自定义触发 jenkins 构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/bash  
# 第一个参数为分支名称 第二参数为Jenkins回调地址  
  
do_serverhook(){  
    if [ "${refname:11}" = "$1" ];then  
        files=`git log ${new_revision} --name-only -1 | sed '1,/^$/d' | sed '1,/^$/d'`  
          
        count=0  
        trigger_file=''  
          
        for file in ${files}; do  
            dir=`echo $file| grep '/' | awk -F'/' '{print $2}'`  
          
            if [ "${dir}x" == "Pluginsx" -o "${dir}x" == "Sourcex" ];then  
                let count+=1  
                trigger_file=${file}  
            fi  
        done  
          
        if [ $count -gt 0 ];then  
            echo "=== CI: Found UEProject file changed or added. Trigger file is ${trigger_file} ==="  
          
            build_url="$2"  
            result=`curl --connect-timeout 10 -I -s -u "ue4_ci:7ZUGNBetfm2b" ${build_url}`  
            result_code=`echo ${result} | head -n1 | awk '{print $2}'`  
          
            if [ "$result_code" -eq "200" -o "$result_code" -eq "201" ];then  
                echo "=== CI: Success to trigger autobuild for branch dev, return code from jenkins is ${result_code} ==="  
            else  
                echo "=== CI: Failed to trigger autobuild, return code from jenkins is ${result_code} ==="  
            fi  
        fi  
    fi  
}  
  
  
process_revision(){  
    do_serverhook 'release' 'http://build.digi-sky.com/job/ue4/job/WT/job/DSGame/job/DSGame-release/build?token=serverhook'  
}  
  
# enforced custom commit message format  
while read old_revision new_revision refname ; do  
   process_revision  
done  
  
exit 0