jenkins获取git提交并dingding通知

在jenkins里,用git命令获取git commit信息和dingding通知

背景和需求

  • 获取本地的commit记录
  • dingding通知

获取commit

git log获取commit信息

git log大家一定不陌生,git log -p显示log详情,而我现在只是想把用户和commit打印出来,类似jenkins的commit详情页, 更具体的请git log –help查看

1
2
#get log from commit_id to now
git log  --format="%s@%cn" $COMMIT_ID..HEAD --no-merges

但是有个问题,我怎么获取上次成功的呢,因为每次都会删掉git拉取的目录,所以这里我选择折衷的办法 通过在一个地方存上次成功的commit id信息

获取上一次的commit id

由于和系统密切相关,我用了sh,个人觉得python在系统维护起来不如sh, 直接上代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env bash
# used for notify website commit by lqx at 2021/06/04 v1.
WEB_DIR="/root/website-jenkins"
WORKSPACE="/root/.jenkins/workspace"

while getopts n:j:u:e:c:t:p:r: OPTION
do
    case $OPTION in
        j)JOBNAME=$OPTARG;;
        u)USER=$OPTARG;;
        e)WEBENV=$OPTARG;;
        c)CHECKURL=$OPTARG;;
        t)TOKEN=$OPTARG;;
        p)GIT_PROJECT=$OPTARG;;
        n)JOBNUMBER=$OPTARG;;
        r)RESULT=$OPTARG;;
        ?)echo "use bash $0 -j $JOBNAME -u $USER -e $ENV -c $CHECK -t $TOKEN -p $GIT_PROJECT" && exit 1;;
    esac
done
JOBURL="http://xxxx/job/${JOBNAME}/${JOBNUMBER}/console"

[ -d $WEB_DIR ] || mkdir -p $WEB_DIR

# write commits to dir
COMMITS=''
for project in $(echo $GIT_PROJECT | tr ',' ' ');do
    if [ -f $WEB_DIR/${JOBNAME}_${project}.commit ];then
        LAST_SUCCESS_COMMIT=$(cat $WEB_DIR/${project}.commit)
    else
        LAST_SUCCESS_COMMIT="HEAD"
    fi
    cd $WORKSPACE/${JOBNAME}/$project
    COMMITS="${COMMITS}$(git log  --format="%s by %cn\n" ${LAST_SUCCESS_COMMIT}..HEAD)"
    [ $RESULT == "成功" ] && echo $(git log|head -n 1|awk '{print $NF}' 2>/dev/null) > $WEB_DIR/${JOBNAME}_${project}.commit
done

[ -z $COMMITS ] && echo '无提交' || echo $COMMITS


# check url link
CHECK='不通过'
[ $(curl -XGET -sIL -w "%{http_code}\n" ${CHECKURL} -o /dev/null) == '200' ] && CHECK='通过'


message="""
##xxxx通知\n
**版本变更环境:** ${WEBENV}\n
**变更job名称:** ${JOBNAME}\n
**版本构建触发人:** ${USER}\n
**url健康检查:** ${CHECK} \n
**当前build结果:** ${RESULT} \n
**本次修改内容:** \n
${COMMITS}
\n
[查看详情](${JOBURL})
"""
curl -XPOST "https://oapi.dingtalk.com/robot/send?access_token=${TOKEN}" -H 'Content-Type: application/json' -d "{\"msgtype\": \"markdown\",\"markdown\":{\"title\":\"${WEBENV}变更通知\",\"text\":\"$message\"}}" && echo "发送成功" || echo "发送失败""}"")"

需要注意一下,

  • 需要传入跟踪的git project,当然我自己偷懒没有去workspace下遍历
  • 还通过curl增加了一个url检查
  • 只有成功的时候才会刷新commit id
  • jenkins对应success failure abort对应传入result, user通过user插件就好了