1. 程式人生 > >Gitee碼雲通過WebHooks實現自動同步程式碼部署

Gitee碼雲通過WebHooks實現自動同步程式碼部署

碼雲(Gitee)的WebHooks功能,可以在我們每次提交程式碼後,向我們設定的地址post一個更新的json資訊,這樣我們就可以根據該資訊,來自動拉去我們的程式碼,實現自動同步功能.

第一步 配置WebHooks

在[碼雲](https://gitee.com/)上,自己的專案中,選擇"管理" --> "WebHooks",這個時候你能看到下圖介面.
注:1 URL填寫為自己接收端的地址,配置後,每次程式碼更新後會通過該地址傳送更新的訊息.
   2 密碼:可以不填寫.

這裡寫圖片描述

第二步 伺服器指令碼配置

在儲存好指令碼檔案後,注意一下事項:
1 該指令碼必須在PHP環境中執行,其他環境根據情況修改.
2 需要將該檔案訪問地址,替換到第一步的URL中.
3 根據實際情況,修改指令碼中的引數:savePath,gitPath,email ,name.
4 isClone 變數,第一次clone的時候,需要設定成false,已經clone過後,需要設定成true.
<?php

//git webhook 自動部署指令碼
//專案存放物理路徑,第一次clone時,必須保證該目錄為空
$savePath = "/www/wwwroot/eia/server/";
$gitPath  = "https://gitee.com/jerry_hui/tools.git";//程式碼倉庫
$email = "your email";//使用者倉庫郵箱
$name  = "your name";//倉庫使用者名稱,一般和郵箱一致即可

$isClone = false;//設定是否已經Clone到本地,true:已經clone,直接pull,false:先clone.

//如果已經clone過,則直接拉去程式碼
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; $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; file_put_contents("git-webhook_log.txt", $res_log, FILE_APPEND);//寫入日誌到log檔案中 } }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; file_put_contents("git-webhook_log.txt", $res, FILE_APPEND);//寫入日誌到log檔案中 }

注意事項

  1. 如果倉庫是公開的,那麼上述配置則不需要修改,因為公開的倉庫,在pull的時候,不需要賬戶和密碼.
  2. 如果倉庫是私有的,那麼還需要做一下配置:
    Windows配置:
    1 進入 C:\Documents and Settings\xxx.,找到.git-credentials檔案,
    touch .git-credentials

    2 用記事本修改.git-credentials.格式如下:
    https://{ username }:{ password }@ xxx .com
    eg:https://zhangsan:[email protected]

    3 在任意目錄 開啟git-bash,輸入:
    git config –global credential.helper store

    4 執行完後去檢視 C:\Documents and Settings\Administrator.gitconfig 這個檔案,發現多了一項:
    [credential] helper = store

    5 重新使用git pull.此時便不再需要輸入密碼.

    Linux配置:
    1 進入 /home/chinaestone(有些在root下面),找到.git-credentials檔案,

    2 輸入內容如下:
    https://{username}:{password}@github.com
    eg:https://zhangsan:[email protected]

    3 儲存檔案退出後,輸入以下指令:
    git config –global credential.helper store

    4 此時在/home/chinaestone/.gitconfig 會新增一項
    helper = store

    5 重新使用git pull.此時便不再需要輸入密碼.