一:先说下整体思路:在服务器中创建远程仓库A(裸仓库,git钩子触发库)和本地仓库B(一般仓库,项目git代码库)。然后在仓库A中创建使B git pull A的脚本,并每当有用户 git push A的时候就触发该脚本。
在服务器CentOS创建Git远程仓库
环境:CentOS 7
1. 安装git
2. 创建一个新用户--www (可以是任意的用户,只需要在下面配置chown用户权限的时候对应即可,不然脚本可能权限不足无法更新代码,保证更新脚本有足够的权限更新代码)
adduser www #添加用户www
passwd www #更改www的密码
#然后按照提示连输2次密码
3. 收集用户公钥,创建证书登录
cd /home/www/
mkdir .ssh
chmod 755 .ssh
touch .ssh/authorized_keys
chmod 644 .ssh/authorized_keys
然后将所有登陆用户的公钥保存在 authorized_keys 中,一行一个。
4. 初始化仓库 /home/mycode/test.git (名称可选后缀必须为.git)
cd /home
mkdir mycode
chown www mycode/ #更改所属用户
cd mycode
git init --bare test.git #初始化仓库
chown -R www test.git #更改所属用户
5. 本地克隆仓库
## 地址为ip 加钩子脚本代码路径
git clone www@127.0.0.1:/home/mycode/test.git
#www 应当更换为你的服务器用户名
#127.0.0.1应当更换为你的服务器IP地址
添加自动更新脚本钩子
1. 初始化两个仓库
两个仓库的目录分别是 A:/home/mycode/test.git 和 B:/home/www/test.git
创建仓库A可以参考。
cd /home
mkdir mycode
##如果需要指定用户执行下面
chown www mycode/
cd mycode
#注意,这里要初始化为一般仓库而非裸仓库
git init test
##如果需要指定用户
chown -R www test
创建仓库B则如同在本地创建仓库一样
2. 在仓库A中配置hooks
cd /home/mycode/test.git/hooks
vi post-receive
然后输入如下内容并保存
#!/bin/sh
unset GIT_DIR
#进入仓库B目录
cd /home/www/test.git
#执行git pull命令
git pull /home/mycode/test.git master
#返回仓库A并退出
cd /home/mycode/test.git
exit 0
赋予其权限
chmod +x /home/mycode/test.git/hooks/post-receive
然后我们在本地向仓库A中 push 文件后就可以在仓库B中看到该文件。
本地 .sh脚本 一个批处理命令,用于提交修改代码并触发钩子自动更新服务器代码
#!/bin/sh
git pull
git add 文件
## 判断是否传参可以声明commit
if [ ! -n "$1" ] ;then
commit_name='测试'
else
commit_name=$1
fi
git commit -m $commit_name
git push origin 提交的项目分支名
##触发服务器钩子
cd 本地地址+/mycode/test
echo "`date +%s` $@" >> test.txt
git add test.txt
git commit -m 'test'
git push origin master