gitgitlabgitlab-cigitlab-ci-runnergitlab-api

Try accept a mr in gitlab-ci, sometime get "Branch cannot be merged"


I try to implement a auto workflow in gitlab-ci.yml which provide a stage named "auto_check" that trigger by gitlab merge_request_event.In this stage, it try rebase, and check the mr title, if "#force_mr" in title then try accept the mr by Rest Api. It works fine sometime, but pipeline often runs fail, I check the log, get [Invoke-RestMethod : {"message":"Branch cannot be merged"}]. After pipeline fail, I retry the pipeline, and it would works fine. It make me so confused. Would be the Merge Tain process still running made my pipeline fail? Appreciate for your help. Here is my ci script:

auto_mr_check:
  stage: auto_check
  tags:
    - windows
  script:
    - |
      $headers = @{
        sometoken
      }
      $mrTitle = $env:CI_MERGE_REQUEST_TITLE
      Write-Output "Merge Request title: $mrTitle"
      
      $rebaseUrl = "$($env:CI_API_V4_URL)/projects/$($env:CI_PROJECT_ID)/merge_requests/$($env:CI_MERGE_REQUEST_IID)/rebase"
      Invoke-RestMethod -Uri $rebaseUrl -Method Put -Headers $headers

      if ($mrTitle -match "#force_mr") {
        Write-Output "Found keyword in title, attempting to merge..."
        $mergeUrl = "$($env:CI_API_V4_URL)/projects/$($env:CI_PROJECT_ID)/merge_requests/$($env:CI_MERGE_REQUEST_IID)/merge"
        Invoke-RestMethod -Uri $mergeUrl -Method Put -Headers $headers
      } else {
        Write-Output "Keyword not found in title, skipping merge."
      }
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: on_success
  variables:
    GIT_STRATEGY: none # Do not clone the repository

check the gitlab doc. search the ci mr in google.


Solution

  • I had figure out the reason. When we create a mr, gitlab will cheack the mr status which is [merge_status] in api response. When the merge_status is "checking", try to accept the mr will get a [Branch cannot be merged] error.

    I fixed my script by polling the merge_status and try accept the mr when the merge_status isn't "checking".

    Here is an issue which enlighten me.