如何在gitlab上使用hooks

参考链接:gitlab git hooks

1. Git Hook 介绍

与许多其他版本控制系统一样,Git 有一种方法可以在发生某些重要操作时,触发自定义脚本,即 Git Hook(Git 钩子)。

当我们初始化一个项目之后,.git 目录下有一个 hooks 目录,可以看到上图左侧有很多执行任务,比如 pre-commit,代表在运行这些命令之后或之前,会进行一些校验和检测来执行相应任务。

Git Hook 分为两部分:本地和远程,如下图所示:

本地 Git Hook,由提交和合并等操作触发:

  • 比如代码发生变更,进行 git add,把 message 进行 commit changes;
  • 当 git commit 时,就会执行一个钩子叫 pre-commit(准备提交钩子)。

远程 Git Hook,运行在网络操作上,例如接收推送的提交:

  • 在 commit 之后,要推送到远端,此时有一个叫 pre-push 钩子,把信息推送 git 仓库;
  • 在远程阶段,极狐GitLab 相当于一个远程仓库。如图有很多仓库,分别承担不同功能,比如 pre-receive ,主要在服务器端接收通过本地推上来代码,然后 update 相关代码,post-receive 说明代码接受成功,同时有一个服务器钩子执行。

在这里,我们主要关注本地 hook,比如说 pre-message 和 pre-push,因此我们会借助这些工具来实现规范化代码内容。

2. 实战操作

2.1 gitlab配置

参考git hooks

复制代码
gitaly['custom_hooks_dir'] = "/var/opt/gitlab/gitaly/custom_hooks"

gitlab-ctl reconfigure

2.2 编写脚本

功能说明:对git的commit信息的前缀做限制

复制代码
mkdir -p /var/opt/gitlab/gitaly/custom_hooks/pre-receive.d/

cat /var/opt/gitlab/gitaly/custom_hooks/pre-receive.d/pre-receive.sh

复制代码
#!/bin/bash
while read oldrev newrev refname; do
    # 从标准输入读取每个引用的旧版本、新版本和引用名称
    commits=$(git rev-list --pretty=oneline $oldrev..$newrev)
    # 遍历每个提交信息
    while read commit; do
        # 提取提交信息的前缀
        prefix=$(echo "$commit" | awk '{print $2}' | awk -F ":" '{print $1}')
        # 检查前缀是否符合要求
        if [[ $prefix != "feat" && $prefix != "fix" && $prefix != "hotfix" ]]; then
            echo "Error: Invalid commit prefix in one or more commits:"
            echo "$commit"
            echo "Only commits with prefixes 'feat', 'fix', or 'hotfix' are allowed."
            exit 1
        fi
    done <<< "$commits"
done

给脚本权限,重启gitlab

复制代码
chown -R git.root /var/opt/gitlab/gitaly/custom_hooks/pre-receive.d
chmod +x git.root /var/opt/gitlab/gitaly/custom_hooks/pre-receive.d/pre-receive.sh

3. 测试

测试提交

回退commit

再次提交

相关推荐
Qperable1 天前
gitlab-runner提示401 Unauthorized
后端·gitlab
西瓜er1 天前
Docker 一键部署指南:GitLab、Nacos、Redis、MySQL 与 MinIO 全解析
redis·docker·gitlab
yunson_Liu2 天前
jenkins更新了gitlab后出现报错
运维·gitlab·jenkins
stark张宇2 天前
Git 与 GitHub 协同工作流:从0到1搭建版本控制体系
git·gitlab·github
牛马的人生7 天前
GitLab入门教程:打开DevOps全流程的大门
运维·其他·gitlab·devops
水冗水孚8 天前
Ubuntu服务器上使用docker-compose部署 gitlab(图文并茂记录)
gitlab
<花开花落>9 天前
gitlab-runner 再次实践中理解和学习
gitlab
Vahala0623-孔勇11 天前
CI/CD流水线优化:GitLab CI镜像构建加速实战
ci/cd·gitlab
Lin_Aries_042111 天前
部署 GitLab 服务器
linux·运维·服务器·docker·gitlab·github
FreeBuf_11 天前
GitLab高危漏洞可致实例崩溃(CVE-2025-10858 和 CVE-2025-8014)
gitlab