How to retrieving always the branch name from BRANCH_NAME and CHANGE_BRANCH environment variables in Jenkins multibranch projects?

huangapple go评论58阅读模式
英文:

How to retrieving always the branch name from BRANCH_NAME and CHANGE_BRANCH environment variables in Jenkins multibranch projects?

问题

在我的 Jenkins 多分支项目中:

  • 当构建分支时,BRANCH_NAMEGIT_BRANCH 会设置为分支的名称(master),而 CHANGE_BRANCH 不存在。
BRANCH_NAME=master
GIT_BRANCH=master
CHANGE_BRANCH 不存在
  • 当构建变更请求时,CHANGE_BRANCH 会设置为分支的名称(feature),而 BRANCH_NAMEGIT_BRANCH 会设置为变更请求的名称(PR-01)。
BRANCH_NAME=PR-01
GIT_BRANCH=PR-01
CHANGE_BRANCH=feature

在我的 声明性流水线 中,无论是否构建变更请求,我始终需要分支名称。

目前,我使用 bash 中的参数扩展来解决这个问题:

sh 'echo branch name: ${CHANGE_BRANCH:-${BRANCH_NAME}}'

是否有更符合 Jenkins 的方法来解决这个问题?

英文:

I'm working on a Jenkins multibranch project and

  • when a branch is built, BRANCH_NAME and GIT_BRANCH is set to the name of the branch (master) and CHANGE_BRANCH does not exist
BRANCH_NAME=master
GIT_BRANCH=master
CHANGE_BRANCH not exist
  • when a change request is built, CHANGE_BRANCH is set to the name of the branch (feature) and BRANCH_NAME and GIT_BRANCH is set to the change request name (PR-01).
BRANCH_NAME=PR-01
GIT_BRANCH=PR-01
CHANGE_BRANCH=feature

> 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; if corresponding to some kind of change request, the name is generally arbitrary (refer to CHANGE_ID and CHANGE_TARGET).

> GIT_BRANCH
> The remote branch name, if any.

> CHANGE_BRANCH
> For a multibranch project corresponding to some kind of change request, this will be set to the name of the actual head on the source control system which may or may not be different from BRANCH_NAME. For example in GitHub or Bitbucket this would have the name of the origin branch whereas BRANCH_NAME would be something like PR-24.

In my declarative pipeline i always need the branch name regardless if a change request or not is built.

Currently i solve this with parameter expansion in bash:

sh 'echo branch name: ${CHANGE_BRANCH:-${BRANCH_NAME}}'

Is there a more Jenkins-oriented approach to solving this?

答案1

得分: 1

When building pull requests, a variable named CHANGE_ID is set (to the PR number). You can use that variable to select between the two other variables:

def always_branch = env.CHANGE_ID ? env.CHANGE_BRANCH : env.BRANCH_NAME
英文:

When building pull requests, a variable named CHANGE_ID is set (to the PR number). You can use that variable to select between the two other variables:

def always_branch = env.CHANGE_ID ? env.CHANGE_BRANCH : env.BRANCH_NAME

huangapple
  • 本文由 发表于 2023年5月22日 21:53:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定