Home
Linux
Golang
MySQL
PHP
Other
Git钩子的使用
创建日期:2019-11-07 16:26:18
更新日期:2023-12-01 13:38:04
栏目:
Linux
浏览:1617
关于 Git 钩子是啥,有什么好处啊,乱七八糟的介绍请自行百度,我的博客只介绍纯干货 > 注:本文主要是以 gitee.com 的 WebHooks 演示,GitHub、Gitlab 等都是大同小异 ## 设置 WebHooks 在仓库首页找到管理,点击进去,找到 WebHooks 设置,设置一个 URL 链接地址和触发事件(当有相应的事件发生时,会给这个 URL 一个 POST 请求),也可以设置密码啥的,避免有人误操作接口。码云发送 POST 请求的请求头和数据结构请看官方介绍。 ## 准备脚本 当码云给这个 URL 发送 POST 请求的时候,我们要正确的来处理它。 - 判断是否是码云请求过来的 - 判断密码是否正确 - 处理你的请求,是 `git pull` 还是发送邮件,触发什么等都可以 直接上代码,用代码说话 ``` // 项目存放物理路径,如果是第一次clone代码,必须保证该目录为空 $savePath = '/www/laravel_dev/'; // 代码仓库,建议最好用SSH方式,可以避免很多麻烦 $gitPath = 'git@gitee.com:shuxiaoyuan/laravel_dev.git'; // 仓库邮箱 $email = 'sxy@shuxiaoyuan.com'; // 仓库用户名 $name = 'sxy@shuxiaoyuan.com'; // 设置是否已经Clone到本地 true:已经clone,直接pull false:先clone $isClone = true; // 密码判断和判断是否是码云请求过来的,在调用这个 function 时就已经判断了。 if ($isClone) { $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; // 直接 pull 代码,采用的是 shell_exec 函数 $res .= shell_exec("cd {$savePath} && git pull {$gitPath} "); $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 .= $res . PHP_EOL; $res_log .= "pull end --------" . PHP_EOL; // 写入日志到log文件中 file_put_contents("git-webhook_log.txt", $res_log, FILE_APPEND); } } else { $res = "clone start --------" . PHP_EOL; // 注:在这里需要设置用户邮箱和用户名,不然后面无法拉去代码 $res .= shell_exec("git config --global user.email {$email} ") . PHP_EOL; $res .= shell_exec("git config --global user.name {$name} ") . PHP_EOL; $res .= shell_exec("git clone {$gitPath} {$savePath}") . PHP_EOL; $res .= "clone end --------" . PHP_EOL; // 写入日志到log文件中 file_put_contents("git-webhook_log.txt", $res, FILE_APPEND); } ``` ## 下面才是重点 - 权限问题:因为这是一段 PHP 代码,所以执行的用户是 php-fpm ,这时候就要去看你的 php-fpm 运行的用户和用户组是啥(默认是 www ),我一般是会改掉了的。 ``` vim /etc/php-fpm.d/www.conf ## 找到 user 和 group 看下用户是什么,或者修改成相应的 ## 下面是我的配置,我的是 shuxiaoyuan:nginx ; Start a new pool named 'www'. [shuxiaoyuan] ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user's group ; will be used. ; RPM: apache Choosed to be able to access some dir as httpd user = shuxiaoyuan ; RPM: Keep a group allowed to write in log dir. group = nginx ``` 确保你脚本里 `$savePath = '/www/laravel_dev/';` 的这个路径,php-fpm 运行用户有可写权限,解决了这个基本就没啥问题了。 - 关于 shell_exec 函数说明:***当PHP在安全模式下运行时,此功能被禁用***,如果发现执行了上面的操作后还是不可以,就去检查这个
内容版权声明:本文为舒孝元原创文章,转载无需和我联系,但请注明来自
舒孝元博客:https://www.shuxiaoyuan.com/info/45
联系邮箱:sxy@shuxiaoyuan.com