Git提交之后自动打版本并钉钉通知

1,012 阅读2分钟

我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

在gitlab的服务器上,进入gitlab的数据目录\

cd /var/opt/gitlab/git-data/repositories/xxx/hooks/post-receive\

利用git的钩子post-receive

post-receive是在提交代码到服务器之后自动执行 然后进入/www/wwwroot/hook.com/git/test.git/hooks

复制一份post-receive.sample 并改名为post-receive [root@iZbp1938t1plpi1gikahmmZ hooks]# cp post-receive.sample post-receive 1 然后编辑 post-receive 添加如下代码 保存退出

DIR=/www/wwwroot/hook.com/public
git --work-tree=${DIR} clean -fd

git --work-tree=${DIR} checkout --force

修改post-receive 文件的权限

chmod -R 777 post-receive

以下是本地配置 在本地上新建一个文件夹 然后添加为远程仓库 // 初始化一个git仓库 git init // 添加远程链接 把192.168.1.1 换成你真实服务器的ip git remote add origin root@192.168.1.1:/www/wwwroor/hook.com/git/test.git

推送时会提示如下错误

然后直接执行如下代码

git push --set-upstream origin master

然后输入你的服务器密码即可

然后去到服务端 服务端直接更新了

原ruby文件里,加上

system "/opt/gitlab/embedded/service/gitlab-shell/hooks/post-receive-shell #{refs}"

调用shell脚本。

shell脚本内容:

#!/bin/bash
data="$(git show --stat)"
string=$data
if [ "$3" == "refs/heads/master" ]; then
    last=$(git rev-list --tags --max-count=1)
    if [ $last ]; then
        tag=$(git describe --tags `git rev-list --tags --max-count=1`)
        tagnum=${tag#*v}
        let tagnum+=1
        tag="v"$tagnum
        $(git tag -a $tag -m 'master')
    else
        tag="v1000"
        $(git tag -a $tag -m 'master')
    fi
    path=$(basename `pwd`)
    commit=$(git log --no-merges -n1 | grep "commit" | awk -F" " '{ print $2}')
    author=$(git log --pretty=format:"%an" $commit -1)
    message=$(git log --pretty=format:"%s" $commit -1)
    /usr/bin/curl -s 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx' \
    -H 'Content-Type: application/json' \
    -d '{"msgtype": "text",
        "text": {
             "content": "仓库:'$path'\r\n版本号:'$tag'\r\n提交人:'$author'\r\n备注:'$message'\r\n请去http://jenkins.fu51.cn 部署"
        }
      }'
fi

结果示意图:

2452132304.png

坑的地方:

1.不能删除原ruby脚本,否则gitlab在merge request时会提示找不到源分支,所以在保留原来的基础上,再调用shell脚本。
2.curl要写绝对路径 /usr/bin/curl。在不写绝对路径的时候,手动运行脚本可以成功,手动push到master分支可以成功,但是通过gitlab页面merge request时无法运行,迷一样的问题。
3.修改之后会出现一个问题

error: unable to write sha1 filename ./objects/10/773c980a96148af4e9fd12c23ecc1e0924c2ad: Permission denied
To gitlab.fu51.cn:wechat_3d_community/cmit_3dsq_server.git
 ! [remote rejected]   test6 -> test6 (unable to migrate objects to permanent storage)
error: failed to push some refs to 'git@gitlab.fu51.cn:wechat_3d_community/cmit_3dsq_server.git'

将gitlab的data目录设置为git的用户

chown -R git:git /var/opt/gitlab/git-data