Issue
We have a multibranch pipeline on jenkins.
I know one can check whether a branch matches the name e.g.
when {
branch "master"
}
Unfortunately our default branch is not named master and the name of the default branch changes regularly.
Is there a way to check if a given branch is the default branch without checking the name?
when {
branch is default
}
or something like this?
Thanks in advance!
Solution
You can use the API of your SCR to get the default branch. Depending on what SCR you use, the call to the API will be different.
In GitLab, you can query the Project REST API and in the response you will find a default_branch
field containing this information
GET /projects/:id
In GitHub, you can query the Repositories REST API and in the response you will find a default_branch
field containing this info as well.
GET /repos/:owner/:repo
Be careful with the GitHub response because it contains 3 fields named default_branch
, one for the actual repo, one for the parent repo, and the last one for the source repo. You are looking for the one on the root of the json, which is the one for the repo you are querying.
Answered By - matus
Answer Checked By - Katrina (JavaFixing Volunteer)