使用管道作为代码时,从 Jenkins 声明性管道中的 Git 中提取分支名称

Extract branch name from Git in Jenkins declarative pipeline when using pipeline as code

我正在开发 Jenkins 声明式管道,只要发布分支发生变化,管道就会触发。 发布分支以这种格式命名: release/v1.0 , release/v2.0 等

我们正在使用下面的 Git PollSCM 阶段来检查何时创建新的发布分支。

stage ('git checkout')
    {
        steps
        {
            checkout poll:true, scm: ([$class: 'GitSCM',
            branches: [[name: 'origin/release/*']],
            userRemoteConfigs: [[credentialsId: "${GIT_CREDENTIALS_ID}", url: "${GIT_URL}"]]
            ])
        }    
    }

我在从发布分支获取版本号时遇到问题,即如果我当前的发布分支是“release/v1.0”,我想从发布名称中提取“v1.0”。

当我使用 echo "${env.BRANCH_NAME}" 时,它 returns 我的“管道即代码”存储库的分支名称,而不是我在“git 结帐”中提到的分支名称舞台.

我可以使用以下代码在声明性管道中获取当前结帐分支名称。

阶段 ('git checkout')

{
    steps
    {
        script
        {
         def scmVars = checkout poll:true, scm: ([$class: 'GitSCM',
        branches: [[name: 'origin/release/*']],
        userRemoteConfigs: [[credentialsId: "${GIT_CREDENTIALS_ID}", url: "${GIT_URL}"]]
        ])
        def releaseName=scmVars.GIT_BRANCH
        
        }
    } 

}