create a variable named GITLAB_API_TOKEN and paste your token
File: ./.pipeline/create-merge-request.sh
#!/usr/bin/env bash# Extract the host where the server is running, and add the URL to the APIs[[$HOST=~ ^https?://[^/]+ ]]&&HOST="${BASH_REMATCH[0]}/api/v4/projects/"# Look which is the default branchTARGET_BRANCH=`curl--silent"${HOST}${CI_PROJECT_ID}"--header"PRIVATE-TOKEN:${PRIVATE_TOKEN}"| python3 -c"import sys, json; print(json.load(sys.stdin)['default_branch'])"`;# The description of our new MR, we want to remove the branch after the MR has# been closedBODY="{
\"id\": ${CI_PROJECT_ID},
\"source_branch\": \"${CI_COMMIT_REF_NAME}\",
\"target_branch\": \"${TARGET_BRANCH}\",
\"remove_source_branch\": true,
\"title\": \"WIP: ${CI_COMMIT_REF_NAME}\",
\"squash\": true,
\"assignee_id\":\"${GITLAB_USER_ID}\"
}";# Require a list of all the merge request and take a look if there is already# one with the same source branchLISTMR=`curl--silent"${HOST}${CI_PROJECT_ID}/merge_requests?state=opened"--header"PRIVATE-TOKEN:${PRIVATE_TOKEN}"`;COUNTBRANCHES=`echo ${LISTMR}|grep-o"\"source_branch\":\"${CI_COMMIT_REF_NAME}\""|wc-l`;# No MR found, let's create a new oneif[${COUNTBRANCHES}-eq"0"];thencurl-X POST "${HOST}${CI_PROJECT_ID}/merge_requests"\--header"PRIVATE-TOKEN:${PRIVATE_TOKEN}"\--header"Content-Type: application/json"\--data"${BODY}";echo"Opened a new merge request: WIP: ${CI_COMMIT_REF_NAME} and assigned to you";exit;fiecho"No new merge request opened";
File: ./.gitlab-ci.yml
image: alpine
stages:- prepare
prepare:open-mr:image: python:3stage: prepare
before_script:[]# We do not need any setup work, let's remove the global one (if any)only:- /^(feature|bugfix|hotfix)\/*/# We have a very strict naming conventionscript:- HOST=${CI_PROJECT_URL} CI_PROJECT_ID=${CI_PROJECT_ID} CI_COMMIT_REF_NAME=${CI_COMMIT_REF_NAME} GITLAB_USER_ID=${GITLAB_USER_ID} PRIVATE_TOKEN=${GITLAB_API_TOKEN} ./.pipeline/create-merge-request.sh # The name of the scriptcache:{}allow_failure:true