码云(Gitee)的WebHooks功能,可以在我们每次提交代码后,向我们设定的地址post一个更新的json信息,这样我们就可以根据该信息,来自动拉去我们的代码,实现自动同步功能.
第一步 配置WebHooks
1.在[码云](https://gitee.com/)上,自己的项目中,选择"管理" --> "WebHooks",
2.这个时候你能看到下图界面.
注:1 URL填写为自己接收端的地址,如:http://xxx.xxx.com/webhook.php,配置后每次代码更新后会通过该地址发送更新的消息.
2 密码:可以不填写.
第二步 服务器脚本配置
1.登陆服务器执行
#生成www用户的公钥
sudo -Hu www ssh-keygen -t rsa
2.将此SSH公钥配置到gitee.com 设置中
cat /home/www/.ssh/id_rsa.pub
3.http://xxx.xxx.com/webhook.php 文件代码如下
<?php
//git webhook 自动部署脚本
$savePath = '/www/wwwroot/xxx.xxx.com/';
$gitPath = 'git@gitee.com:xxx/xxx.xxx.com.git';//代码仓库
$remoteName = 'xxx';//远程仓库别名
$branch = 'master';//分支
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
die('send fail');
}
//解析Git服务器通知过来的JSON信息
$content = json_decode($requestBody, true);
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master' && $content['total_commits_count']>0) {
$res = PHP_EOL."pull start --------".PHP_EOL;
$res .= shell_exec("cd {$savePath} && git pull {$remoteName} {$branch}");//拉去代码
$res_log = '-------------------------'.PHP_EOL;
$res_log .= $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '个commit:';
$res_log .= "sudo -Hu www cd {$savePath} && sudo -Hu www git pull {$remoteName} {$branch}";
$res_log .= $res.PHP_EOL;
$res_log .= "pull end --------".PHP_EOL;
file_put_contents("git-webhook_log.txt", $res_log, FILE_APPEND);//写入日志到log文件中
// $result = shell_exec("cd {$savePath} && git pull {$remoteName} {$branch}");
// echo $result;exit;
}