Rahul Desai
Rahul Desai

Reputation: 309

Gitlab merge from a specific source branch

I have a branch in gitlab called devops and i want to merge my master branch with devops branch. However, i do not want any other branch to issue a merge request with devops branch. Is it possible?

Basically, for devops as the target branch while merging, only master can be the source branch. Can some customizations be done to be able to do this? Or by using any scripts?

Upvotes: 4

Views: 6838

Answers (1)

MrBerta
MrBerta

Reputation: 2748

As far as I know, there is no easy way to tell GitLab which branches that are allowed to be merged into which other branches. If you are using GitLab CI there is a way to achieve what you want though.

If you go to your project on GitLab, then to Settings -> General -> Merge Requests. There you will find a checkbox that says "Only allow merge requests to be merged if the pipeline succeeds".

Then you have to set up a pipeline for your project, and you should be able to find tutorials and documentation for this. There are then two environment variables called "CI_MERGE_REQUEST_SOURCE_BRANCH_NAME" and "CI_MERGE_REQUEST_TARGET_BRANCH_NAME". These are set by GitLab when the pipeline is running in a merge request context.

Here is a list of all variables that are predefined. https://docs.gitlab.com/ce/ci/variables/#predefined-environment-variables

You can then set up a job that is run before all other jobs, but only if there is a merge request. There is no use to check these variables otherwise! An example can look like this:

stages:
  - merge-check
  - build
  - test

allowed-merge:
  stage: merge-check
  script:
    - check-branches # This command is different depending on if you run cmd/bash 
  only:
   - merge_requests

The script for checking the branch name can look different depending on where your gitlab runner is executing. It should check these two environment variables and return 0 if the branches are correct and return 1 otherwise.

Doing it this way doesn't stop the merge requests from being created, but there is no way to accept a merge request that doesn't follow the rules that you want.

Upvotes: 7

Related Questions