提交代码到远程GIT仓库,代码自动同步到远程服务器上

现在一般都会通过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就会请求我们设置的脚本,进行拉取代码。

相关文章

Git安装和使用 Git安装和使用 刚开始用git的小白适用,,转自...
fatal: remote origin already exists.解决方法 第一个问题g...
git常用命令(二)查看历史记录 git log [--pretty=oneline]...
git之如何把本地文件上传到远程仓库的指定位置 git专栏收录该...
代码规范之 lint-staged 在代码提交之前,进行代码规则检查能...
方法:1、文件没有git操作时用“git checkout--文件”命令还...