安装git,生成公钥,加公钥 都有教程,需要注意的是以下几个方面
php以www用户执行,需要给到权限才能执行git pull
用合适的工具干合适的活,php去操作git pull只是在测试环境图方便搞的,如果正式环境,应该考虑用其他方式,例如系统定时任务设置触发条件等。
1、vim /etc/sudoers
root下加一行
www localhost=(ALL) NOPASSWD:/usr/bin/git (安装git后目录用which git查看)
2、允许php执行exec shell_exec
3、改目录权限
4、.git改权限可写,我直接改成777了
5、.git/config https地址改成ssh的
header("Content-type: text/html; charset=utf-8");
$js = json_decode($_REQUEST["hook"]); // json转换
if ($js->password != "password") {
die("ERROR!"); // 判断密码
}
$fp = fopen("./log.txt", 'a');
$lastcommit = $js->push_data->commits[count($js->push_data->commits) - 1]; // 获取最后的commit
if (strstr($lastcommit->message, "release")) // 这里意为:如果最后的commit包含"release"则进行自动发布。
{
exec("cd ./"); // 进入目录
exec("git pull origin master"); // 进行git拉取,前提是使用了ssh
fwrite($fp, "※" . date('Y-m-d H:i:s') . "\t" . $lastcommit->message . "\t" . $lastcommit->author->name . "\n"); // 进行记录
} else {
fwrite($fp, date('Y-m-d H:i:s') . "\t" . $lastcommit->message . "\t" . $lastcommit->author->name . "\n");
}