如何在Laravel应用中触发指定目录Git命令并推送至BitBucket仓库
Laravel 实现访问指定地址自动提交BitBucket仓库的方案
1. 新增路由
在routes/web.php文件中添加如下路由定义:
use App\Http\Controllers\DeployController; Route::get('/deploy', [DeployController::class, 'pushToBitbucket']);
2. 创建控制器
执行Artisan命令生成控制器文件:php artisan make:controller DeployController
3. 编写控制器业务逻辑
打开app/Http/Controllers/DeployController.php,填入如下代码:
<?php namespace App\Http\Controllers; use Illuminate\Http\Response; use Symfony\Component\Process\Process; class DeployController extends Controller { public function pushToBitbucket() { // 目标仓库本地路径 $repoPath = public_path('repo.name'); // 按顺序执行的git命令列表 $commandList = [ 'git add .', 'git commit -m "Changes"', 'git push' ]; $executionLog = []; foreach ($commandList as $command) { $process = Process::fromShellCommandline($command, $repoPath); $process->run(); // 处理执行结果 if (!$process->isSuccessful()) { // 兼容无改动时commit跳过的场景 if (str_contains($process->getErrorOutput(), 'nothing to commit')) { $executionLog[] = '无待提交改动,跳过commit步骤'; continue; } return response()->json([ 'status' => 'failed', 'failed_command' => $command, 'error_msg' => $process->getErrorOutput() ], Response::HTTP_INTERNAL_SERVER_ERROR); } $executionLog[] = sprintf('命令[%s]执行成功:%s', $command, $process->getOutput()); } return response()->json([ 'status' => 'success', 'execution_log' => $executionLog ]); } }
4. 必要前置配置
- 确认Laravel运行用户(常见为www-data、nginx)对
public/repo.name目录及其下.git文件夹拥有读写执行权限 - 提前在服务器配置BitBucket的访问凭证,推荐使用SSH密钥认证,避免执行git push时需要手动输入账号密码
- 生产环境使用时必须给
/deploy路由加访问限制,比如IP白名单、接口密钥校验,避免被恶意调用
提示:如果需要自定义commit信息,可以在接口中加参数传入,替换硬编码的"Changes"即可。
内容的提问来源于stack exchange,提问作者Bal Sankar
相关产品推荐
相关产品推荐

