如何通过脚本/插件/流水线提取Jenkins的Last Commit Activity信息?
提取Jenkins用户的Last Commit Activity信息
你提到的Last Commit Activity数据并非存储在hudson.model.User对象中,而是由Git(或其他SCM)插件从构建的变更记录中收集并聚合的。以下是两种可行的提取方式:
方式一:Groovy脚本直接提取(控制台/流水线通用)
通过遍历Jenkins的构建记录,提取每个提交者的最新活动信息并聚合:
import hudson.model.User import jenkins.model.Jenkins import hudson.plugins.git.GitChangeSet // 存储用户最后提交信息:键为用户ID,值为[最后提交时间, 对应流水线名称] def userLastCommitMap = [:] // 遍历所有启用的流水线 Jenkins.instance.getAllItems(hudson.model.Job).each { job -> if (!job.isDisabled()) { // 取最近100次构建(可根据性能调整数量) job.getBuilds().take(100).each { build -> if (build.getResult() != null && build.getChangeSets()) { build.getChangeSets().each { changeSet -> // 针对Git变更集处理(其他SCM需替换对应ChangeSet类型) if (changeSet instanceof GitChangeSet) { changeSet.getAuthors().each { author -> // 通过提交者邮箱匹配Jenkins用户 def user = User.get(author.getEmailAddress(), false, null) if (user) { def userId = user.getId() def commitTime = new Date(changeSet.getTimestamp()) // 更新用户的最新提交记录 if (!userLastCommitMap.containsKey(userId) || commitTime.after(userLastCommitMap[userId][0])) { userLastCommitMap[userId] = [commitTime, job.getName()] } } } } } } } } } // 输出最终结果 User.getAll().each { user -> def userId = user.getId() def fullName = user.getFullName() def commitInfo = userLastCommitMap.get(userId) if (commitInfo) { println("User ID - ${userId}, Full Name - ${fullName}, Last Commit Activity - ${commitInfo[0]}, Pipeline - ${commitInfo[1]}") } else { println("User ID - ${userId}, Full Name - ${fullName}, Last Commit Activity - 无近期提交记录") } }
注意事项:
- 若使用SVN等其他SCM,需替换对应的
ChangeSet类型(如hudson.scm.SubversionChangeLogSet) - 调整
take(100)的数值可平衡性能与数据完整性,避免遍历全量构建导致Jenkins卡顿 - 若提交者邮箱与Jenkins用户ID不匹配,需修改用户匹配逻辑(例如用提交者用户名匹配)
方式二:调用Jenkins API接口
asynchPeople页面的数据直接来自Jenkins内置API,可通过以下接口获取结构化数据:
GET /asynchPeople/api/json?depth=2
返回的JSON中,users数组包含每个用户的lastCommitActivity、fullName、id及关联流水线信息,可直接解析使用。
流水线中调用示例:
若在Jenkins流水线中使用,可借助httpRequest插件发起请求并解析:
pipeline { agent any stages { stage('获取用户提交信息') { steps { script { def response = httpRequest( url: "${JENKINS_URL}/asynchPeople/api/json?depth=2", authentication: 'jenkins-api-user', // 需配置对应凭据 contentType: 'APPLICATION_JSON' ) def userData = readJSON text: response.content userData.users.each { user -> println("${user.id} | ${user.fullName} | 最后提交:${user.lastCommitActivity}") } } } } } }
内容的提问来源于stack exchange,提问作者josh.dev.1
相关产品推荐
相关产品推荐

