gitee nginx php 项目 自动化拉取

GITEE 配置:WebHooks
URL:  http://域名/authHook.php
密码: 配置好 需要填写到 authHook.php 文件里

image

authHook.php

<?php
// 本地站点目录
$local = '/www/wwwroot/test';

// 密码 gitee项目管理webhook中设置
$password = 'A*****7oyZ';

//如果请求体内容为空,返回错误
$payload = file_get_contents('php://input');
if (!$payload) {
    header('HTTP/1.1 400 Bad Request');
    die('HTTP HEADER or POST is missing.');
}

// gitee默认返回json,解析json后验证密码
$data = json_decode($payload, true);
if(empty($data) || $data['password'] != $password) {
    header('HTTP/1.1 403 Permission Denied');
    die('Permission denied.');
}

// 如果仓库目录不存在,返回错误
if (!is_dir($local)) {
    header('HTTP/1.1 500 Internal Server Error');
    die('Local directory is missing');
}
//输出执行结果 包括错误信息,在gitee webhook中可以查看和测试
$res = shell_exec("cd {$local} && git pull 2>&1");
echo $res;
$res_log = '-------------------------'.PHP_EOL;
$res_log .= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push '.$res.PHP_EOL;
file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//将每次拉取信息追加写入到日志里
die("done " . date('Y-m-d H:i:s', time()));

服务器端 .git/config 需要修改url 参数 在原来的 url 基础上添加 用户名:gitee密码@ 

原来的:

https://gitee.com/username/test.git

修改后:

https://username:password@gitee.com/username/test.git

服务器端 修改 .git 目录 和 .git/FETCH_HEAD 文件为 可写权限
如没有 FETCH_HEAD 创建这个文件 vi FETCH_HEAD 空内容直接保存就可以了

chmod -R 777 .git
chmod -R 777 .git/FETCH_HEAD

 服务器端 当前版本php 需要启用 shell_exec() 函数 注意该函数对服务器安全有一定风险 如果在意 请勿开启

测试:

本地提交代码,服务器端 自动 pull ,autoHook.php 同级目录会生成一个 hook日志文件 git-webhook.txt 


image