0%

git和gitlab的hook

1. hook介绍

客户端钩子由诸如提交和合并这样的操作所调用,而服务器端钩子作用于诸如接收被推送的提交这样的联网操作。

客户端钩子位于项目根目录 your_project/.git/hooks 文件夹下。

服务端钩子则位于 your_project.git 文件夹下的 hooks 和 custom_hooks。

600

1. Git hook

钩子都被存储在Git目录下的hooks子目录中。也即绝大部分项目中的.git/hooks。这些示例的名字都是以 .sample 结尾,如果想启用它们,移除这个后缀即可。

注意: 客户端 hooks 并不会同步到版本库中。可以自定义 githook地址,可以把脚本提交到仓库,但是需要每个客户端配置 core.hooksPath,见makefile。

1.1 .githook/pre-commit

pre-commit 是在键入提交信息前运行,如果该钩子以非零值退出,Git 将放弃此次提交,不过你可以用 git commit –no-verify 来绕过这个环节。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash  

PROJECT=$(git rev-parse --show-toplevel)
cd $PROJECT

echo -e "Protobuf namespace conflict detection hook start..."

bash $PROJECT/namespace_detection.sh # 这里是我的脚本
ret=$?
if [ $ret -eq 1 ]; then
echo -e "\nProtobuf namespace conflict detection failed!!!"
exit 1
fi


echo -e "Protobuf namespace conflict detection ok."
exit $?

1.2 Makefile

1
2
3
4
5
6
7
8
.PHONY: init  
init:
# git hook init.
git config core.hooksPath .githooks

.PHONY: all
all:
make init;

2. Gitlab hook

服务端 git hook 分为三种,分别是 pre-receive、update、post-receive,这三个步骤就是我们本地 push 完代码服务端要做的事情。

img
  • pre-receive:git push 向仓库推送代码时被执行。
  • update:在pre-receive之后被调用。它也是在实际更新前被调用的,但它可以分别被每个推送上来的引用分别调用。也就是说如果用户尝试推送到4个分支,update会被执行4次。不需要读取标准输入。
  • post-receive:在成功推送后被调用,适合用于发送通知。这个脚本没有参数,但和pre-receive一样通过标准输入读取

2.1 pre-receive

根据钩子类型需要在仓库存储路径下的custom_hooks(不存在就自行创建)文件下创建对应钩子类型名称的脚本文件。

1
2
3
mkdir /var/opt/gitlab/git-data/repositories/@hashed/项目hashed路径/custom_hooks
touch /var/opt/gitlab/git-data/repositories/@hashed/项目hashed路径.git/custom_hooks/pre-receive
chmod +x /var/opt/gitlab/git-data/repositories/@hashed/项目hashed路径.git/custom_hooks/pre-receive

3. 参考资料

可以加首页作者微信,咨询相关问题!