每当Redis吸收到发布的推送,触发回调,通过SSH客户端实行Git命令。
PHP SSH 客户端
https://nicen.cn/2430.html

HTTP接口吸收来自远程仓库的更新推送,然后把数据进行处理后推送给异步任务。
<?php/ 获取推送的数据 /$json = file_get_contents("php://input");$data = json_decode($json, true);/ 判断推送是否来自指定的用户 /if ($data['user_name'] != "friend-nicen") { exit("造孽要求");}/ 处理数据 /$need = [ "clone" => $data['repository']["clone_url"], //远程仓库地址 "path" => $data['repository']["path"], //远程仓库名 "branch" => str_replace("refs/heads/", '', $data['ref']) //分支];/通过Redis订阅,进行任务投递/getRedis()->publish("RECV_GIT", json_encode($need));exit("正在处理本次更新...");
2.PHP Cli脚本
利用前请先按照https://nicen.cn/2430.html,安装PHP拓展,您须要准备:
Redis的IP和端口SSH账号和密码存放所有仓库的根目录<?phpinclude_once 'vendor/autoload.php';/ 引入SSH客户端 /use phpseclib3\Net\SSH2;/ 创建redis /function getRedis():Redis{ $redis = new Redis(); $redis->connect("IP","端口"); $redis->setOption(3, -1); return $redis;}/链接ssh/$ssh = new SSH2('localhost', 22);/如果登录失落败/if (!$ssh->login('root', '您的SSH密码')) { return;}/ SSH读取消息 /$read = function () use ($ssh) { /拼接/ $raw = ""; /读取空缺次数/ $blank = 0; / 循环读取 / while (true) { $msg = $ssh->read('username@username:~$'); if (!empty($msg)) { $raw .= $msg; } else { / 空缺10次,终止,返回 / if ($blank > 10) { break; } else { $blank++; } } } return $raw;};/读取间隔韶光/$ssh->setTimeout(0.1);$redis = getRedis(); //创建redis/ 打开存放仓库的目录 /$root = "/home/repos/"; //存放仓库的目录$ssh->write("cd " . $root . "\n");echo $read(); //读取初始化的/ Redis订阅等待 /$redis->subscribe(["RECV_GIT"], function ($redis, $chan, $msg) use ($ssh, $read, $root) { echo "收到:" . $msg . "\n"; //收到 / 判断内容是否包含分支信息 / if (strpos($msg, "branch") === false) return; try { $data = json_decode($msg, true); //处理结果 / 判断仓库是否存在 / $path = $root . $data['path']; //本地仓库路径 / 仓库目录是否存在 / if (!file_exists($path)) { /创建/ mkdir($path); /打开仓库目录/ $ssh->write("cd " . $path . "\n"); /初始化仓库/ $ssh->write("git init\n"); echo $read(); //读取后续的 /添加远程仓库/ $ssh->write("git remote add origin " . $data['clone'] . "\n"); echo $read(); //读取后续的 } else { /打开仓库目录/ $ssh->write("cd " . $path . "\n"); } /拉取分支/ $ssh->write("git pull origin " . $data['branch'] . ":" . $data['branch'] . " \n"); echo $read(); //读取后续的 } catch (\Throwable $e) { echo $e->getMessage() . "\n"; }});
3.运行脚本
打开上方Cli脚本所在目录,运行如下命令:
# 前台运行php 文件名.php # 后台台运行nohup php 文件名.php &
每次脚本运行的日志,会自动写入到当前目录的nohup.out文件,作为日志方便不雅观察同步结果 ;
运行之后,每次仓库有更新,脚本都会自动同步这一次的更新;本文只是大略的实现,您完备可以通过这个案例实现更繁芜的功能。