如何从 Jenkins Pipeline 获取 pull request id

How to get pull request id from Jenkins Pipeline

我正在尝试使用 Jenkins 管道通过 Sonar 分析我的源代码。要让 Sonar 将结果通知 Github,我需要指定 Pull Request ID。

我如何从 Jenkins Pipelines 获取这个 Pull Request ID?

我们正在使用 GitHub Organization Folder Plugin 构建拉取请求,而不是 GitHub pull request builder plugin。这就是 $ghprbPullId 对我不起作用的原因。关于如何以不同方式获取拉取请求 ID 的任何想法?

你通过env.BRANCH_NAME.

得到PR号
if (env.BRANCH_NAME.startsWith('PR-')) {
    def prNum = env.BRANCH_NAME.replace(/^PR-/, '')
    ...
}

Jenkins 公开了一个名为 CHANGE_ID:

的全局变量

For a multibranch project corresponding to some kind of change request, this will be set to the change ID, such as a pull request number.

此变量仅为拉取请求构建填充,因此您必须在分支源的管道配置中禁用分支构建并启用 PR 构建:

我的流水线步骤如下所示:

def PULL_REQUEST = env.CHANGE_ID

stage('Analysis') {
        withCredentials([[$class: 'StringBinding', credentialsId: '***', variable: 'GITHUB_ACCESS_TOKEN']]) {
            withSonarQubeEnv('Sonar') {
                withMaven(maven: 'M3') {
                    sh "mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar " +
                            "-Dsonar.analysis.mode=preview " +
                            "-Dsonar.github.pullRequest=${PULL_REQUEST} " +
                            "-Dsonar.github.oauth=${GITHUB_ACCESS_TOKEN}"
                }
            }
        }
    }

如果 Thomas 的回答不起作用或不适用于您,您也可以(可能)使用分支名称通过查询 Github REST API.您只需要一个 API 令牌和分支名称,按更新日期 DESC 的顺序查找拉取请求,并找到与您的分支名称匹配的第一个 PR。那将有 Pull Request 编号。

这仅适用于每个拉取请求都有唯一的分支名称(例如 JIRA 问题票号)。