<h2 >要求</h2><p >实现<code >git push</code>直接完成代码部署到服务器的目录</p><h2 >实现方式</h2><p >利用<code >git</code>的hooks中的<code >post-receive</code>来实现代码提交完成之后的动作。将仓库指定一个<code >--work-tree</code>然后进行检出操作<code >checkout --force</code></p><h2 >目录结构</h2><p >我自己的项目结构是这样的,每一个仓库对应一个项目,例如<code >public/wx</code>项目对应<code >repo/wx.git</code>仓库</p><pre class="hljs typescript" >. ├──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</pre><p >再看下hooks文件目录</p><pre class="hljs css" >. ├──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</pre><p >我们将<code >post-receive.sample</code>复制一份<code >post-receive</code>,并且编写代码如下</p><pre class="hljs properties" >#指定我的代码检出目录DIR=/www/public/wxgit--work-tree=${DIR}clean-fd#直接强制检出git--work-tree=${DIR}checkout--force</pre><h2 >如何生成目录</h2><p >上面看到的repo目录中的<code >wx.git</code>实际上是一个裸仓库,我们用下面的命令来生成这样一个仓库。</p><pre class="hljs properties" >cd/www/repogitinit--barewx.git</pre><p >对于代码部署目录和仓库我们已经通过<code >post-receive</code>进行了关联了,因为我们一旦将代码push到仓库,那么会自动检出到<code >publish/wx</code>目录下。</p><h2 >远程部署</h2><p >在本地电脑上,我们添加远程仓库</p><pre class="hljs groovy" >gitinit gitremoteaddoriginroot@xxx.xxx.xxx.xxx:/www/repo/wx.git</pre><p >这个时候我们添加了远程仓库,那么我们来测试下<code >push</code>操作</p><pre class="hljs properties" >touchindex.phpgitadd.gitcommit-m&#39;test&#39;gitpush</pre><p >可能会提示一个<code >--set-upstream</code>,直接执行下就好了。执行完之后我们登陆服务器,会发现文件已经出现在<code >public/wx/index.php</code></p><h2 >注意点</h2><ol class=" list-paddingleft-2"><li><p>如果我们没有配置<code >ssh免密码登陆</code>的话,我们需要在<code >push</code>代码的时候输入密码</p></li><li><p>如果我们添加的远程仓库不是<code >root@xxx.xxx.xx.xx</code>,例如是<code >abc@xx.xx.xx.xx</code>,那么我们要确保<code >abc</code>用户对<code >wx.git</code>目录下的文件有<code >777</code>权限。</p></li></ol><h3 >新增仓库</h3><ol class=" list-paddingleft-2"><li><p>需要登陆远程服务器进行初始化<code >repo_name.git</code>仓库</p></li><li><p>需要手动创建<code >public/repo_name</code>文件夹,并且修改权限为777</p></li><li><p>需要重新编写<code >hooks/post-recieve</code>文件,修改里面的DIR路径为<code >public/repo_name</code></p></li></ol>
T:0.059737s,M:247.29 KB
返回顶部 留言