git Jenkins 管道分支名称返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43770058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 12:44:29  来源:igfitidea点击:

Jenkins pipeline branch name returns null

gitjenkinsgroovy

提问by pogorman

I'm trying to get the name of my branch for a jenkins groovy script. I cannot get the current branch name. I try the following:

我正在尝试获取 jenkins groovy 脚本的分支名称。我无法获得当前的分支名称。我尝试以下操作:

stage('Check out code')
checkout scm
echo "My branch is: ${env.BRANCH_NAME}"

Here is the output - it always returns null.

这是输出 - 它总是返回 null。

 Checking out Revision 33b531b2f1caaf8b64d968e437306f39d2dba1da   (origin/pipeline)
  > git.exe config core.sparsecheckout # timeout=10
  > git.exe checkout -f 33b531b2f1caaf8b64d968e437306f39d2dba1da
 [Pipeline] echo
 My branch is: null

Am I missing something?

我错过了什么吗?

回答by pogorman

This variable only works in a multibranch pipline:

此变量仅适用于多分支管道:

BRANCH_NAME For a multibranch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches.

BRANCH_NAME 对于多分支项目,这将设置为正在构建的分支的名称,例如,如果您希望从 master 而不是从功能分支部署到生产。

I was testing in a normal pipline

我在正常的管道中测试

回答by b.ben

My workaround, Don't know if work for someone else..

我的解决方法,不知道是否为其他人工作..

def branchName = getCurrentBranch()
echo 'My branch is' + branchName

def getCurrentBranch () {
    return sh (
        script: 'git rev-parse --abbrev-ref HEAD',
        returnStdout: true
    ).trim()
}

回答by VonC

git.exe checkout -f 33b531b2f1caaf8b64d968e437306f39d2dba1da

That would make the git repo enter a detached HEADmode, which, by its very nature, has no branch.

这将使 git repo 进入分离的 HEAD模式,就其本质而言,它没有分支。

From Jenkinsfile:

Jenkinsfile

The checkout step will checkout code from source control; scmis a special variable which instructs the checkout step to clone the specific revision which triggered this Pipeline run.

checkout 步骤将从源代码管理中检出代码;scm是一个特殊变量,它指示结帐步骤克隆触发此流水线运行的特定修订。

So the ${env.BRANCH_NAME}is null.

所以${env.BRANCH_NAME}是空的。

As mentioned in "Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT", you can get the SHA1 you just checked out with the groovy syntax (to be adapted in a Jenkins pipeline DSL):

正如“ Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT”中提到的,您可以使用groovy语法获取您刚刚检出的SHA1(在Jenkins管道DSL中进行调整):

sh 'git rev-parse HEAD > commit'
def commit = readFile('commit').trim()

回答by sdc

I had this same issue, but I resolved it by changing

我有同样的问题,但我通过更改解决了它

println "${env.BRANCH_NAME}"

to

println "${BRANCH_NAME}"

Note my plugin is also checking out in detached mode:

请注意,我的插件也在分离模式下检查:

git checkout -f e10a170e17fb5f9282f903a7b3cd17bd2e181dee