WebHooks实现git提交自动同步到服务器
1.首先在我们项目的根目录下创建webhooks.php
<?php
$json = file_get_contents("php://input");
$data = json_decode($json,true);
$data['password']=='xxxxx'; // webhook设置的密码,可为空
if (isset($data['ref']) && $data['total_commits_count']>0 && $data['password']=='xxxxx') {
$res = PHP_EOL."pull start ---------------------------------------------".PHP_EOL;
$res .= shell_exec("cd /www/wwwroot/xxx && git pull https://username:password@gitee.com/xxx/xxx.git 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']['message'];
$res_log .= $res.PHP_EOL;
$res_log .= "pull end -----------------------------------------------------".PHP_EOL;
var_dump($res_log);// 这个打印会显示在WebHooks的事件中
file_put_contents("log/webhook/".date('Y-m-d',time()).".txt", $res_log, FILE_APPEND);//写入日志到log文件中
}else{
file_put_contents("log/webhook/".date('Y-m-d',time()).".txt", $json , FILE_APPEND);//写入日志到log文件中
}
?>
2.然后在仓库中设置webhooks
3.再次提交就会发现服务器已经可以自动同步了
- 常见问题
-
1.shell_exec()无法使用,shell_exec()被禁用
- php.ini exec()函数无法使用
原因:在php.ini的 disable_functions配置中,默认exec执行函数都是被 禁止的,需要在php.ini中disable_functions = exec , popen, system …. ,将你需要用的函数从列表中删掉,然后在重启就可以了
- php.ini exec()函数无法使用
-
2.error: cannot open .git/FETCH_HEAD: Permission denied
- 权限问题,全部设置为www权限755
-