前言
在项目开发中使用git进行代码的管理,每次完成更改上传代码后,还需要登录服务器将代码拉取下来.现在git服务器(gitee/gitlab/github)都会有Webhooks功能,以实现在向git仓库推送/合并等时机让服务器自动拉取新代码。
前言
使用Webhooks后,整个上传部署流程如下:
服务器端操作
webhook脚本创建
关于推送的post数据格式,参考码云的《WebHook 推送数据格式说明》.根据这个参数格式编写php的脚本文件如下:
<?php
//本地路径(服务器上的git项目地址)
$local = '/www/wwwroot/test';
$json = file_get_contents("php://input");
$data = json_decode($json, true);
//获取推送分支
$branch = str_replace('refs/heads/', '', $data['ref']);
if (isset($data['ref']) && $data['total_commits_count'] > 0) {
$res = PHP_EOL . "pull start ---------------------------------------------" . PHP_EOL;
$res .= shell_exec("cd " . $local . " && git pull origin master 2<&1");
$res_log = '------------------------------------------------------------' . PHP_EOL;
$res_log .= $data['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $data['repository']['name'] . '项目的' . $data['ref'] . '分支push了' . $data['total_commits_count'] . '个commit:' . $data['commits'][0]['message'];
$res_log .= $res . PHP_EOL;
$res_log .= "pull end -----------------------------------------------------" . PHP_EOL;
// 文件路径
$filePath = $local . "/public/logs/webhook/" . date('Ym', time()) . "/";
// 路径不存在则创建
!is_dir($filePath) && mkdir($filePath, 0755, true);
//写入日志到log文件中
file_put_contents($filePath . date('Y-m-d', time()) . ".txt", $res_log, FILE_APPEND);
}
服务器用户设置
git pull 操作的时候出现error: insufficient permission for adding an object to repository database .git/objects错误,下面记录解决办法,供后续查找。默认为www,切换到root,在根目录下对.git文件夹赋值权限
chmod -R 777 .git
git仓库操作
在码云上打开项目仓库,依次点击[管理]=>[WebHooks]=>[添加],填写webhook的php脚本地址,如有需要填写webhook密码/密钥(密钥需要再添加验签),如下图