|
| 1 | +#!/usr/bin/env bash |
| 2 | +# Extract the host where the server is running, and add the URL to the APIs |
| 3 | +[[ $HOST =~ ^https?://[^/]+ ]] && HOST="${BASH_REMATCH[0]}/api/v4/projects/" |
| 4 | + |
| 5 | +# Look which is the default branch |
| 6 | +TARGET_BRANCH=`curl --silent "${HOST}${CI_PROJECT_ID}" --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" | python3 -c "import sys, json; print(json.load(sys.stdin)['default_branch'])"`; |
| 7 | + |
| 8 | +# The description of our new MR, we want to remove the branch after the MR has |
| 9 | +# been closed |
| 10 | +BODY="{ |
| 11 | + \"id\": ${CI_PROJECT_ID}, |
| 12 | + \"source_branch\": \"${CI_COMMIT_REF_NAME}\", |
| 13 | + \"target_branch\": \"${TARGET_BRANCH}\", |
| 14 | + \"remove_source_branch\": true, |
| 15 | + \"title\": \"WIP: ${CI_COMMIT_REF_NAME}\", |
| 16 | + \"assignee_id\":\"${GITLAB_USER_ID}\" |
| 17 | +}"; |
| 18 | + |
| 19 | +# Require a list of all the merge request and take a look if there is already |
| 20 | +# one with the same source branch |
| 21 | +LISTMR=`curl --silent "${HOST}${CI_PROJECT_ID}/merge_requests?state=opened" --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}"`; |
| 22 | +COUNTBRANCHES=`echo ${LISTMR} | grep -o "\"source_branch\":\"${CI_COMMIT_REF_NAME}\"" | wc -l`; |
| 23 | + |
| 24 | +# No MR found, let's create a new one |
| 25 | +if [ ${COUNTBRANCHES} -eq "0" ]; then |
| 26 | + curl -X POST "${HOST}${CI_PROJECT_ID}/merge_requests" \ |
| 27 | + --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" \ |
| 28 | + --header "Content-Type: application/json" \ |
| 29 | + --data "${BODY}"; |
| 30 | + |
| 31 | + echo "Opened a new merge request: WIP: ${CI_COMMIT_REF_NAME} and assigned to you"; |
| 32 | + exit; |
| 33 | +fi |
| 34 | + |
| 35 | +echo "No new merge request opened"; |
0 commit comments