平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“服务器上搭建git仓库与钩子hook的配置过程”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。
服务器上的git目录下文件设置
结合项目来看,本服务器是基于阿里云上的服务器,服务器上的web服务在/wwwroot/www目录下
ssh root/用户名@服务器地址,进入服务器
cd /home/git/ #进入git目录
git init --bare huang.git #初始化一个git仓库


结合项目来看,需先在服务器上添加个Git用户组,同时在git用户组里添加个git用户,后面的操作都是采用git这个用户身份操作的。因为我是root权限登录的,所以是root权限,这处必须要修改的。
chown -R git:git huang.git/


理解这一步时,此时,git目录下的huang.git文件夹git用户组修改完毕,下面是修改hook,此处不详述钩子的作用,这里只说明如何用,详细能够自己去查询了解。
钩子hook
理解这一步时,进入刚新建的huang.git文件夹里的hooks文件夹中,里面有post-receive和post-update这两个文件(如果没有的话需自己新建)
下面是设置好的post-receive里的文件内容:
#!/bin/sh
#
# An example hook script for the "post-receive" event.
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
#
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
# cd /wwwroot/www/你的项目文件名(这里为huang)
cd /wwwroot/www/huang
env -i git pull
下面是设置好的post-update里的文件内容:
#!/bin/sh
#
# An example hook script for the "post-receive" event.
#
# The "post-receive" script is run after receive-pack has accepted a pack
# and the repository has been updated. It is passed arguments in through
# stdin in the form
#
# For example:
# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master
#
# see contrib/hooks/ for a sample, or uncomment the next line and
# rename the file to "post-receive".
#. /usr/share/git-core/contrib/hooks/post-receive-email
cd /wwwroot/www/huang
env -i git pull
web目录下文件设置
在这个场景下,git目录下的文件设置完毕,下面进入web目录/wwwroot/www。将git目录下刚新建的空仓库的内容clone过来,命令如下所示:

ls -la
chown -R git:git huang/

本地clone远程项目
落到代码里,到此,服务器上的仓库文件设置完毕。在本地clone远程服务器上的空仓库,命令如下所示:
git clone git@服务器地址:huang.git
进入该项目文件夹,添加代码文件
git add .
git commit -m "1"
git push

结合项目来看,这个时候git目录下的代码会得到更新,同时由于钩子的作用,web目录(/wwwroot/www)下的代码也得到了同步更新。
理解这一步时,若web目录下的代码没有更新,可能是版本产生冲突了,能够在web目录下的项目文件夹(/wwwroot/www/huang)下git pull一下,这样代码就能够正常维护了。
注意,出现如下所示问题时:
remote: error: insufficient permission for adding an object to repository database ./objects
remote: fatal: failed to write object
error: unpack failed: unpack-objects abnormal exit
客户端机器对服务器git代码仓库的写权限出了问题。
在这个场景下,改变代码仓库下,所有文件的访问权限,同组可写,确认严格按照上面的指令执行。
chown -R *
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多兼容脚本之家。
- 采用gitlab在服务器上搭建私服git仓库同时上传项目的操作方法
- Github库镜像到本地私有Gitlab服务器实现过程
- gitlab-ci设置服务器自动拉取方式
- 如何在CentOS 7上搭建GitLab服务器(完整指南)
- Linux 服务器如何用 SSH 拉取多个 Git 工程

