GIT自动打版本并通知到钉钉

@liubb  March 17, 2020

git提交之后自动打版本并钉钉通知
在gitlab的服务器上,进入gitlab的数据目录
/var/opt/gitlab/git-data/repositories/xxx/hooks/post-receive
利用git的钩子,post-receive是在提交代码到服务器之后自动执行

原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

结果示意图:
WX20200318-202154@2x.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

添加新评论