简体   繁体   English

如何在詹金斯共享库中获取分支名称

[英]How to get branch name in jenkins shared library

I'm trying to write my first Jenkins shared library and I'm struggling with something basic - getting the branch name. 我正在尝试编写我的第一个Jenkins共享库,并且正在尝试一些基本的工作-获取分支名称。

I could do: 我可以做:

sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

However, that requires a checkout. 但是,这需要签出。 Would it be possible to get the branch name (for both multibranch and freestyle) pipeline projects? 是否可以获得分支名称(对于多分支和自由样式)管道项目? I know I'll be using git, but I would like to avoid doing a checkout (until it is necessary). 我知道我将使用git,但我想避免进行结帐(除非有必要)。

The GIT_BRANCH environment variable should give you what you want. GIT_BRANCH环境变量应为您提供所需的内容。 It won't work in pipeline until Jenkins 2.60 and upgraded pipeline model definition plugin. 直到Jenkins 2.60和升级的管道模型定义插件,它才能在管道中工作。

If you are using a pipeline job, you can 如果您正在使用管道作业,则可以

  • Capture object returned from scm checkout 捕获从scm签出返回的对象
  • Reference environment variable 参考环境变量

pipeline {
    // ...
    stages {
        stage('Setup') {
            steps {
                script {
                    // capture scm variables
                    def scmVars = checkout scm
                    String branch = scmVars.GIT_BRANCH

                    // or use the environment variable
                    branch = env.GIT_BRANCH
                }
            }
        }
        // ...
    }
}

Environment variable reference. 环境变量参考。

I ended up using this: 我最终使用了这个:

 env.CHANGE_BRANCH ?: env.GIT_BRANCH ?: scm.branches[0]?.name?.split('/')[1] ?: 'UNKNOWN'

However, this requires me to approve several things in In-Script Approvals page. 但是,这需要我In-Script Approvals页面中批准几件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM