如何获取 Jenkinsfile 中已更改文件的列表以获取拉取请求?
How to get list of changed files in Jenkinsfile for a pull request?
是否可以在拉取请求构建期间获取 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
}
}
}
但如果我是第一次构建新分支,此方法不会 return 任何更改,因为没有以前的构建可以与之比较。有人找到解决办法了吗?
谢谢
据我所知,没有 built-in 功能可以做到这一点。
幸运的是,您可以通过编程方式找到它:
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()
}
是否可以在拉取请求构建期间获取 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
}
}
}
但如果我是第一次构建新分支,此方法不会 return 任何更改,因为没有以前的构建可以与之比较。有人找到解决办法了吗?
谢谢
据我所知,没有 built-in 功能可以做到这一点。
幸运的是,您可以通过编程方式找到它:
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()
}