问题描述
在请求请求构建期间是否可以在Jenkinsfile中获取已更改文件的列表?我目前正在这样做...
def changeLogSets = currentBuild.rawBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles)
for (int k = 0; k < files.size(); k++) {
def file = files[k]
print file.path
}
}
}
但是如果我是第一次构建新分支,则此方法不会返回任何更改,因为没有以前的构建可与之进行比较。有没有人找到解决方案?
谢谢
解决方法
据我所知,没有内置功能可以做到这一点。
幸运的是,您可以通过编程找到答案:
def local_branch = sh (
script: "git rev-parse --abbrev-ref HEAD",label: "Getting current branch name",returnStdout: true
).trim()
println "Local branch is ${local_branch}"
def base_branch = 'master'
// This is very naive.
// In reality,you need a better way to find out what your base branch is.
// One way is to have a file with a name of a base branch.
// Another one is to invoke API,e.g. GitHub API,to find out base branch.
// Use whatever works for you.
println "Base branch is ${base_branch}"
sh script: "git fetch origin --no-tags ${base_branch}",label: "Getting base branch"
def git_diff = sh (
script: "git diff --name-only origin/${base_branch}..${local_branch}",returnStdout: true
).trim()
现在,您在git_diff
变量中有了已更改文件的列表。
使用Jenkins变更集通常无效,并且保留用于其他目的。
,这也可以通过 pipeline-github 插件实现:
def changedFiles = pullRequest.files.collect {
it.getFilename()
}