Expose MR source and target branch SHA consistently across Merge Request pipeline and Pipeline for Merged Result
Problem
There is no consistent way of obtaining the Head SHA of the merge request source branch, which is the actual commit by the author.
Currently there are the following CI variables to refer to commit SHAs:
Variable | Description | Value in Merge Request pipeline | Value in Pipeline for Merged Result |
---|---|---|---|
CI_COMMIT_SHA | The commit revision the project is built for. | HEAD SHA of the source branch of the merge request | SHA of the merge commit |
CI_MERGE_REQUEST_SOURCE_BRANCH_SHA | The HEAD SHA of the source branch of the merge request. The variable is empty in merge request pipelines. The SHA is present only in merged results pipelines. | empty | HEAD SHA of the source branch of the merge request |
There is no consistent way of obtaining the CI_MERGE_REQUEST_SOURCE_BRANCH_SHA
across different types of pipelines.
Proposal
Always expose CI_MERGE_REQUEST_SOURCE_BRANCH_SHA
and CI_MERGE_REQUEST_TARGET_BRANCH_SHA
including in Merge Request pipeline. The variable names are already self-explanatory, which are the HEAD SHA of the source and target branch.
Define the variable as:
variables.append(key: 'CI_MERGE_REQUEST_SOURCE_BRANCH_SHA', value: source_sha.to_s || (sha.to_s if merge_request?))
The problem is more with CI_MERGE_REQUEST_TARGET_BRANCH_SHA
since we have only Ci::Pipeline#target_sha
defined in Ci::Pipeline
which is provided only in merged result pipeline. In case of detached MR pipelines we would need to read the value from pipeline.merge_request.target_branch_sha
which reflects the latest commit in the repository for the same ref.