GitLab 事件触发 Jenkins 构建只是一个启动信号,获取变更文件列表需要知晓上一次构建时某个仓库的版本号,这里 Jenkins 的插件 git-plugin 已经帮我们实现了这部分工作。所以只需要通过 git-plugin 检出代码即可。
检出代码
checkout([$class:'GitSCM',
branches: [[name: "*/$branchName"]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class:'RelativeTargetDirectory',
relativeTargetDir: "$relativeTarget"]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "$credentialsId", url: "$gitUrl"]]])
请自行替换
$branchName
为分支名,
$relativeTarget
为检出相对路径,
$credentialsId
为用户凭据,
$gitUrl
即 GIT仓库地址。
获取信息脚本demo
pipeline {
agent any
stages {
stage('拉取代码'){
steps {
checkout([$class:'GitSCM',
branches: [[name: "*/$branchName"]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class:'RelativeTargetDirectory',
relativeTargetDir: "$relativeTarget"]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "$credentialsId", url: "$gitUrl"]]])}}
stage('构建代码'){
steps {
script{
List<String> changes = getChangedFilesList()
println ("文件变更列表: " + changes)
String gitCommitId = getGitcommitID()
println("CommitID: " + gitCommitID)
String gitCommitAuthorName = getAuthorName()
println("提交人: " + gitCommitAuthorName)
String gitCommitMessage = getCommitMessage()
println("提交信息: " + gitCommitMessage)}}}}}
//获取变更文件列表,返回HashSet,注意添加的影响文件路径不含仓库目录名
@NonCPS
List<String>getChangedFilesList(){
def changedFiles =[]for( changeLogSet in currentBuild.changeSets){for(entry in changeLogSet.getItems()){
changedFiles.addAll(entry.affectedPaths)}}return changedFiles
}
// 获取提交ID
@NonCPS
String getGitcommitID(){
gitCommitID =" "for( changeLogSet in currentBuild.changeSets){for(entry in changeLogSet.getItems()){
gitCommitID = entry.commitId
}}return gitCommitID
}
// 获取提交人
@NonCPS
String getAuthorName(){
gitAuthorName =" "for( changeLogSet in currentBuild.changeSets){for(entry in changeLogSet.getItems()){
gitAuthorName = entry.author.fullName
}}return gitAuthorName
}
// 获取提交信息
@NonCPS
String getCommitMessage(){
commitMessage =" "for( changeLogSet in currentBuild.changeSets){for(entry in changeLogSet.getItems()){
commitMessage = entry.msg
}}return commitMessage
}
版权归原作者 _zxue 所有, 如有侵权,请联系我们删除。