groovy 脚本实例 检测git提交信息并推送到企业微信
检测git提交信息并推送到企业微信
package common.ecs
import groovy.json.JsonSlurperClassic
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
node('ecs_wuhan_docker') {
properties([
parameters([
string(name: 'setBeginTime', description: '不指定默认使用上一次执行的结束时间,格式:2022-mm-dd', defaultValue: '2022-mm-dd', trim: true)
]),
disableConcurrentBuilds(),
pipelineTriggers([cron('H 10 * * *')]),
buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '7', numToKeepStr: '30')),
])
String project = "ecs2(357)"
String branchName = 'dev'
if (setBeginTime == '2022-mm-dd') {
setBeginTime = sh(returnStdout: true, script: 'date -d -1days "+%Y-%m-%d"').trim()
}
String beginTime = "$setBeginTime" + 'T00:00:00.000Z'
stage('checkout src') {
deleteDir()
cloneProjectBranch(['ecs2'], 'ecs-platform', branchName, 'jenkins')
}
def apiPaths
stage('find client api path') {
dir('ecs2') {
apiPaths = sh(returnStdout: true, script: "find ./ecs -type d -name client|grep api-client").trim()
}
}
String dayStr = sh(returnStdout: true, script: 'date "+%Y-%m-%d"').trim()
def results
def initLength
stage('request commits and file') {
dir('ecs2') {
StringBuffer sb = new StringBuffer("方舟平台client api变化自动检测:\n")
initLength = sb.length()
Map parallelMap = [:]
for (item in apiPaths.split("\\n")) {
def apiPathStr = item
parallelMap.put(apiPathStr.split('/')[2], {
String apiPath = apiPathStr.substring(2)
def commitsObjList = getCommitsByPath(project, beginTime, branchName, apiPath)
for (commitsObj in commitsObjList) {
String commitId = commitsObj.get("commitId")
String fileName = commitsObj.get("fileName")
String authorName = commitsObj.get("authorName")
String taskName = "${fileName}接口变更-" + dayStr
String taskId = createTapdTask(taskName, authorName)
String commitUrl = "https://192.168.48.50/ecs-platform/ecs2/commit/${commitId}"
String desc = "文件变更地址: <a rel=\"noopener\" href=\"${commitUrl}\">${commitUrl}</a>"
String commitMsg = commitsObj.get("commitMsg")
sb.append(commitMsg + '\n')
}
})
}
parallel(parallelMap)
results = sb.toString()
}
}
stage('notice msg') {
print(results)
if (initLength < results.length()) {
wxNotice(results, ['8577f1c3-e3ee-4930-9572-efcac46151d4'])
}
}
}
def createTapdTask(String taskName, String owner) {
String creator = '杜永军'
String workspaceId = '61177290'
String story_id = '1185347'
String password = 'fuS4sCW3:1384FFB8-EC11-CB10-3830-FA6C1D58D896'
String url = "curl -u '${password}' 'https://api.tapd.cn/tasks' " +
"--data-urlencode 'name=${taskName}' \\\n" +
"--data-urlencode 'workspace_id=${workspaceId}' \\\n" +
"--data-urlencode 'story_id=${story_id}' \\\n" +
"--data-urlencode 'owner=${owner}' \\\n" +
"--data-urlencode 'creator=${creator}' \\\n"
String taskId
retry(3) {
String createResultJson = sh(returnStdout: true, script: url).trim()
taskId = new JsonSlurperClassic().parseText(createResultJson).get("data").get("Task").get("id")
}
return taskId
}
def createTaskComments(String description, String taskId) {
String creator = '杜永军'
String workspaceId = '61177290'
String story_id = '1185347'
String password = 'fuS4sCW3:1384FFB8-EC11-CB10-3830-FA6C1D58D896'
String url = "curl -u '${password}' 'https://api.tapd.cn/comments' " +
"--data-urlencode 'workspace_id=${workspaceId}' \\\n" +
"--data-urlencode 'author=${creator}' \\\n" +
"--data-urlencode 'entry_type=tasks' \\\n" +
"--data-urlencode 'entry_id=${taskId}' \\\n" +
"--data-urlencode 'description=${description}' \\\n"
retry(3) {
sh(returnStdout: true, script: url).trim()
}
}
def cloneProjectBranch(projectNames, group, branch, userName) {
withCredentials([usernamePassword(credentialsId: 'ecs_git', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
def encodedPass = URLEncoder.encode(PASS, "UTF-8")
try {
sh 'git config --global http.sslVerify false'
} catch (e) {
}
Map parallelMap = [:]
for (item in projectNames) {
def projectName = item
parallelMap.put(projectName, {
sh "git clone --depth=1 https://${USER}:${encodedPass}@192.168.48.50/${group}/${projectName}.git ${projectName}"
dir(projectName) {
sh "git config user.email ${userName}@yuanian.com"
sh "git config user.name ${userName}"
if (isHasFeature(branch)) {
sh "git checkout ${branch}"
}
}
})
}
parallel(parallelMap)
}
}
def isHasFeature(featureName) {
String featureCount = sh(returnStdout: true, script: "git ls-remote|grep .*/${featureName}\$ | wc -l").trim()
return Integer.parseInt(featureCount) > 0
}
def getCommitsByPath(String projectName, String bgTime, String branchName, String path) {
String projectId = projectName.split("\\(")[1].replace(")", "")
def json = getJsonMsgByPath(projectId, bgTime, branchName, path)
if (json.size() > 0) {
return parseJson(json, path, projectId)
}
return ''
}
def getJsonMsgByPath(String projectId, String bgTime, String branchName, String path) {
echo "----------------本次查询条件: 项目是:$projectId 开始时间:$bgTime 分支:$branchName 路径:$path -------------"
String beginTime = fixBeginTime(bgTime)
String json
withCredentials([string(credentialsId: 'gitLab_token', variable: 'TOKEN')]) {
String curlStr = "https://192.168.48.50/api/v4/projects/${projectId}/repository/commits?ref_name=${branchName}&since=%27${beginTime}%27"
if (path != null) {
curlStr += "&path=" + path
}
json = sh(returnStdout: true, script: "curl -k '${curlStr}' -H 'PRIVATE-TOKEN:${TOKEN}'").trim()
}
return new JsonSlurperClassic().parseText(json)
}
def parseJson(commitsJson, String pathName, projectId) {
Map parallelMap = [:]
def list = []
for (item in commitsJson) {
def commitJson = item
String short_id = commitJson.get("short_id")
parallelMap.put(short_id, {
String message = commitJson.get("message").replaceAll("\n", "")
String author_name = commitJson.get("author_name")
String committed_date = commitJson.get("committed_date")
String commitId = commitJson.get("id")
String commitMsg = "提交人:" + author_name + " 提交时间:" + committed_date.substring(0, committed_date.indexOf("T")) + " 备注:" + message
def diffFileJson = getDiffFileJson(projectId, short_id)
diffFileJson.each { diff ->
String old_path = diff.get("old_path")
if (old_path.contains("api-client/") && old_path.contains("/client/")) {
String modifyPath = old_path.substring(old_path.indexOf('com/'))
String fileName = old_path.substring(old_path.lastIndexOf('/') + 1)
def commitObj = [:]
commitObj.put("commitId", commitId)
commitObj.put("fileName", fileName)
commitObj.put("commitMsg", commitMsg)
commitObj.put("authorName", author_name)
commitObj.put("modifyPath", modifyPath)
list.add(commitObj)
}
}
})
}
parallel(parallelMap)
return list
}
def getDiffFileJson(projectId, short_id) {
String curlStr = "https://192.168.48.50/api/v4/projects/${projectId}/repository/commits/${short_id}/diff"
String json
withCredentials([string(credentialsId: 'gitLab_token', variable: 'TOKEN')]) {
json = sh(returnStdout: true, script: "curl -k '${curlStr}' -H 'PRIVATE-TOKEN:${TOKEN}'").trim()
}
return new JsonSlurperClassic().parseText(json)
}
def fixBeginTime(String beginTime) {
CharSequence cs = beginTime.replace("Z", "")
def day = LocalDateTime.parse(cs, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
day = day.minusHours(8)
return day.toString()
}
def wxNotice(msg, tokenKeys) {
for (tokenKey in tokenKeys) {
sh """
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${tokenKey}' \
-H 'Content-Type: application/json' \
-d '
{
"msgtype": "text",
"text": {
"content": "${msg}",
"mentioned_mobile_list":["@all"]
}
}'
"""
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!