Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git CI/CD variable to get the number of commits behind in merge request pipeline

Need to fail the pipeline in case if the source branch is behind in commits with the target branch

like image 386
Aswath shobi Avatar asked May 11 '26 06:05

Aswath shobi


1 Answers

Since issue 15310 and GitLab 11.6 (Dec. 2018), you can run a pipeline only if it is a merge_request.

That allows you to access $CI_MERGE_REQUEST_TARGET_BRANCH_SHA predefined variable, that you can then use in rules (like ones defined in the gitlab/ci/templates/Workflows/MergeRequest-Pipelines.gitlab-ci.yml.
In your case, a rule specific to test if new commits are added:

test:
  stage: test
  script: ./test
  only:
    - merge_requests
  rules:    
    - if: $CI_COMMIT_TAG

However, a if rule would not allow executing the kind of script git command you would need:

 git merge-base --is-ancestor <maybe-ancestor-commit> <descendant-commit>
 git merge-base --is-ancestor $CI_MERGE_REQUEST_TARGET_BRANCH_SHA CI_MERGE_REQUEST_SOURCE_BRANCH_SHA

If that commands returns 0 (true), the job should process, and the target branch HEAD is an ancestor of the merge request branch, which means the latter only brings new commits directly on top of the former (target) branch.

So I would still have a job running only for merge_requests, executing in a script: directive that git command, and calling your actual script (the one you want to see executed on merge-request "in case if the source branch is behind in commits with the target branch") in a separate stage (called by the first gatekeeper one), using needs: <first-stage>, as in here.

like image 194
VonC Avatar answered May 12 '26 23:05

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!