git利用post-receive自动化部署

要求

实现git push 直接完成代码部署到服务器的目录php

实现方式

利用git的hooks中的post-receive来实现代码提交完成以后的动做。将仓库指定一个--work-tree而后进行检出操做checkout --forcegit

目录结构

我本身的项目结构是这样的,每个仓库对应一个项目,例如public/wx项目对应repo/wx.git仓库web

.
├── public
│   └── wx // 这是咱们的web代码部署目录
│       ├── index.php
│       ├── test2.php
│       ├── test3.php
│       └── test.php
└── repo // 这个是咱们的仓库目录
    └── wx.git // 这个对应wx项目的仓库
        ├── branches
        ├── config
        ├── description
        ├── HEAD
        ├── hooks // post-receive钩子代码写在这里面
        ├── index
        ├── info
        ├── objects
        └── refs

再看下hooks文件目录服务器

.
├── applypatch-msg.sample
├── commit-msg.sample
├── post-commit.sample
├── post-receive
├── post-receive.sample
├── post-update.sample
├── pre-applypatch.sample
├── pre-commit.sample
├── prepare-commit-msg.sample
├── pre-rebase.sample
└── update.sample

咱们将post-receive.sample复制一份post-receive,而且编写代码以下app

# 指定个人代码检出目录
DIR=/www/public/wx
git --work-tree=${DIR} clean -fd
# 直接强制检出
git --work-tree=${DIR} checkout --force

如何生成目录

上面看到的repo目录中的wx.git其实是一个裸仓库,咱们用下面的命令来生成这样一个仓库。ssh

cd /www/repo
git init --bare wx.git

对于代码部署目录和仓库咱们已经经过post-receive进行了关联了,由于咱们一旦将代码push到仓库,那么会自动检出到publish/wx目录下。post

远程部署

在本地电脑上,咱们添加远程仓库测试

git init
git remote add origin root@xxx.xxx.xxx.xxx:/www/repo/wx.git

这个时候咱们添加了远程仓库,那么咱们来测试下push操做code

touch index.php
git add .
git commit -m 'test'
git push

可能会提示一个--set-upstream,直接执行下就行了。执行完以后咱们登录服务器,会发现文件已经出如今public/wx/index.phpip

注意点

  1. 若是咱们没有配置ssh免密码登录的话,咱们须要在push代码的时候输入密码
  2. 若是咱们添加的远程仓库不是root@xxx.xxx.xx.xx,例如是abc@xx.xx.xx.xx,那么咱们要确保abc用户对wx.git目录下的文件有777权限。

新增仓库

  1. 须要登录远程服务器进行初始化repo_name.git仓库
  2. 须要手动建立public/repo_name文件夹,而且修改权限为777
  3. 须要从新编写hooks/post-recieve文件,修改里面的DIR路径为public/repo_name
相关文章
相关标签/搜索