(PHP) git webhook 自動部署腳本

在git管理中配置POST請求該方法對應的路由進行自動調用


 public function giteepush()
    {
        //git webhook 自動部署腳本
        //項目存放物理路徑,第一次clone時,必須保證該目錄爲空
        $isClone = true;//設置是否已經Clone到本地,true:已經clone,直接pull,false:先clone.
        $savePath = '/data/www/project';
        //如果已經clone過,則直接拉去代碼
        if ($isClone) {
            $requestBody = file_get_contents("php://input");
            if (empty($requestBody)) {
                die('send fail');
            }

            //解析Git服務器通知過來的JSON信息
            $content = json_decode($requestBody, true);
            // var_dump($content)
            //若是dev分支且提交數大於0
            if ($content['ref']=='refs/heads/dev' && $content['total_commits_count']>0) {

                $res = PHP_EOL."pull start --------".PHP_EOL;
                // $output = shell_exec("cd /data/www/project && git pull 2>&1");
                $res .= shell_exec("cd {$savePath} && git pull");//拉取代碼
                $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;
                echo $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '項目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '個commit:';
                Log::channel('daily')->info($res_log);

            }else{
                die('非dev分支提交操作不更新');
            }
        }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::channel('daily')->info($res);
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章