git 服务器发布项目,使用 Git Hooks 实现自动项目部署

本文介绍了如何在服务器上设置Git Hooks,特别是使用post-receive钩子,来实现在提交包含特定字符串的commit时自动部署代码。通过在Git仓库的Hooks目录下编辑post-receive脚本,检查提交信息并执行必要的部署条件,确保安全的自动化部署流程。这种方法简化了持续集成过程,并提供了对部署触发条件的控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在某服务器上面搭建 git 开发和部署环境,git 开发环境很简单,按照 ProGit 一书的相关知识就可以轻松搞定,实现了类似 Github 的使用 SSH + 私有 Clone 的方式。

关于部署,实际上是自动部署,起初的想法是使用 bash shell 制定一个定时任务去不断 git pull 产品代码,后来记得 Git 带有 Hooks,索性在 ProGit 一书翻了翻:

Git 本身可以调用自定义的挂钩脚本,其中有两组:客户端和服务器端。客户端挂钩用于客户端的操作,如提交和合并。服务器端挂钩用于 Git 服务器端的操作,如接收被推送的提交。详情请查看 ProGit 相关章节

如果这样就简单了,利用服务器端调用想要的挂钩(Hook),即可实现自动部署的方案,为了保证不被肆意部署,特加了一个对需要部署 commit 的判断,利用读取 commit subject 并匹配想要的字符串才去部署,这样我认为是一个比较安装的部署方案。

Git 的挂钩(Hook)主要包含:

applypatch-msg

post-update

pre-rebase

commit-msg

pre-applypatch

update

post-commit

pre-commit

post-receive

prepare-commit-msg

这里我们只需要使用 post-receive 这个 Hook:在接收 post(push)

请求之后执行。其他大部分我也没有大多研究,不过看名字不算难理解,我觉得其中大部分包含 commit 的属于客户端。

好了,部署开始:

1. 在服务器 git 仓库(注意是 bare 仓库,不是代码仓库)的 Hooks,编辑

post-receive(如果没有自行创建),代码请看:

#!/bin/sh

#

# git autodeploy script when it matches the string "[deploy]"

#

# @author icyleaf

# @link http://icyleaf.com

# @version 0.1

#

# Usage:

# 1. put this into the post-receive hook file itself below

# 2. `chmod +x post-recive`

# 3. Done!

# Check the remote git repository whether it is bare

IS_BARE=$(git rev-parse --is-bare-repository)

if [ -z "$IS_BARE" ]; then

echo >&2 "fatal: post-receive: IS_NOT_BARE"

exit1

fi

# Get the latest commit subject

SUBJECT=$(git log -1 --pretty=format:"%s")

# Deploy the HEAD sources to publish

IS_PULL=$(echo "$SUBJECT" | grep "\[deploy\]")

if [ -z "$IS_PULL" ]; then

echo >&2 "tips: post-receive: IS_NOT_PULL"

exit1

fi

# Check the deploy dir whether it exists

DEPLOY_DIR=/home/icyleaf/php/icyleaf/

if [ ! -d $DEPLOY_DIR ] ; then

echo >&2 "fatal: post-receive: DEPLOY_DIR_NOT_EXIST: \"$DEPLOY_DIR\""

exit1

fi

# Check the deploy dir whether it is git repository

#

#IS_GIT=$(git rev-parse --git-dir 2>/dev/null)

#if [ -z "$IS_GIT" ]; then

#echo >&2 "fatal: post-receive: IS_NOT_GIT"

#exit 1

#fi

# Goto the deploy dir and pull the latest sources

cd $DEPLOY_DIR

#env -i git reset --hard

env -i git pull

这里会先判断脚本所在目录是否是 bare git 仓库,然后获取最新 commit 的 subject,并匹配是否包含 [deploy] 字样,如果包含,则继续检查产品代码仓库路径是否存在,如果存在则执行 git pull 操作。

2. 对刚才编辑的 post-receive 执行下面命令以保证脚本可执行:$ chmod +x post-receive

3. 完成!

对于自定义脚本,其实不仅限于 bash shell,你可以使用你熟悉的语言,然后把你的脚本路径在 hooks 脚本中加载即可。

脚本还会继续更新,下面需要增加关于测试部分的相关判断和部署。 bash shell 还需要进一步学习,上面脚本是我第一次写,如有不妥之处,请指教,感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值