Running pre-merge pipelines
Why validate the correctness of the pull request merge before the actual merge? The reason for that is not immediately apparent, so let’s peek at the example to get a better understanding. There are numerous causes which may lead to the broken main branch after merging feature branch even if both branches are completely fine by themselves while separated.
One of the obvious examples is an update of the main branch right before the merge. Consider this scenario: the feature branch uses a library that was declared as deprecated some time ago. The new push to the main branch removes that library without any notification of the feature branch’s developers.
Both branches pass the CI pipeline. If the feature branch was merged to the main branch, it would fail the pipeline because the deprecated library is no longer available in the main tree.
Validating merge result before the actual merge easily catches this kind of problem.
Executing pre-merge checks in Pull Requests
First step is to add additional stage in the pipeline config (
stages: - pre-merge - … # all other stages pre-merge feature branch: stage: pre-merge only: variables: - $CI_PRE_MERGE commands: - apk add git # you can use image with pre-installed git - git config --global user.email 'snake-ci@pipeline' - git checkout $CI_PULL_REQUEST_TO_HASH - git merge $CI_PULL_REQUEST_FROM_HASH … # rest of the pipeline goes here
This additional step will merge the feature branch locally in the pipeline context.
The specified commands will be executed only if the
is set before the pipeline is triggered.
Such a variable could be set in the popup dialog, which appears when you click on the New Pipeline button at the pull request page, but to automate it a little bit, we can use Run Templates feature to pre-populate this variable for the future use.
To do so, we need to add Run Template with the
$CI_PRE_MERGE variable defined in it.
Navigate to Repository settings → SNAKE CI → Run Templates and click the Add Template button.
Enter a name like “Run pre-merge check” and click the Save & Specify Variables button.
Then click the Add Variables button and add a new variable with the name
CI_PRE_MERGE leaving value empty.
After those changes are made, you can run the final pre-merge check pipeline on all new pull requests by navigating to the pull request you want to merge and clicking the New Pipeline ↓ button, and clicking “Run pre-merge check”.
This action will trigger a new pipeline with the additional
which will merge the feature branch into the main branch before running the pipeline.
If something goes wrong, it will be clearly seen since the pipeline will be failed.
Also, since the pipeline is failed, it prohibits the pull request from being merged until the issue is resolved.