現在一般都會通過github,gitlab,gitee來管理我們的代碼。我們希望只要我本地push了代碼,遠程服務器能自動拉取git倉庫的代碼,進行同步。
這就需要用到各倉庫為我們提供的webhooks了,每當有push操作時,倉庫就會調用我們設置的腳本,通過在腳本里我們運行命令來手動拉取代碼。
這里以gitee為例
一、首先我們在gitee創建一個項目

二、確保我們服務器上安裝了git
> yum install git
三、為了避免git pull時輸入賬號和密碼,我們需要創建.git-credentials
1、先cd到當前用戶目錄
> cd ~
2、然后創建.git-credentials文件
> vi .git-credentials
3、寫入如下數據,注意,用戶名和密碼填上自已的
https://用戶名:密碼@gitee.com
4、運行如下命令
> git config --global credential.helper store
5、查看~/.gitconfig,會發現多一項
[credential] helper = store
6、注意這里只是配置的當前用戶,我php-fpm運行的用戶是www(大家或許會跟我不同),所以我們需要為www也配置.git-credentials

我們把.gitconfig和.git-credentials復制到/home/www下,並設置所屬用戶和組為www
> cp ~/.gitconfig /home/www/ > cp ~/.git-credentials /home/www/ > cd /home/www > chown www.www .gitconfig > chown www.www .git-credentials
四、我們git clone項目代碼
> cd /data/wwwroot/ > git clone https://gitee.com/lackone/test.git
五、由於我們是通過php腳本執行git pull所以,需要給www用戶讀寫test目錄的權限
> chown -R :www /data/wwwroot/test > chmod -R g+w /data/wwwroot/test
六、拉取代碼腳本,注意該腳本一定能外網訪問
<?php
//本地路徑
$local = '/data/wwwroot/test';
//倉庫地址
$remote = 'https://gitee.com/lackone/test.git';
//密碼
$password = '123456';
//獲取請求參數
$request = file_get_contents('php://input');
if (empty($request)) {
die('request is empty');
}
//驗證密碼是否正確
$data = json_decode($request, true);
if ($data['password'] != $password) {
die('password is error');
}
echo shell_exec("cd {$local} && git pull {$remote} 2>&1");
die('done ' . date('Y-m-d H:i:s', time()));
七、配置gitee的webhooks

八、最后我們只要push代碼,gitee就會請求我們設置的腳本,進行拉取代碼。
