Skip to content

Instantly share code, notes, and snippets.

@banyudu
Created August 4, 2020 04:54
Show Gist options
  • Select an option

  • Save banyudu/4cba6a8a9f0977efc7d7708011fdc8df to your computer and use it in GitHub Desktop.

Select an option

Save banyudu/4cba6a8a9f0977efc7d7708011fdc8df to your computer and use it in GitHub Desktop.
Create merge request in gitlab ci
#!/usr/bin/env bash
# Extract the host where the server is running, and add the URL to the APIs
[[ $CI_PROJECT_URL =~ ^https?://[^/]+ ]] && CI_PROJECT_URL="${BASH_REMATCH[0]}/api/v4/projects/"
# Look which is the default branch
#TARGET_BRANCH=`curl --silent "${CI_PROJECT_URL}${CI_PROJECT_ID}" --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" | python3 -c "import sys, json; print(json.load(sys.stdin)['default_branch'])"`;
TARGET_BRANCH="develop"
# The description of our new MR, we want to remove the branch after the MR has
# been closed
BODY="{
\"id\": ${CI_PROJECT_ID},
\"source_branch\": \"${CI_COMMIT_REF_NAME}\",
\"target_branch\": \"${TARGET_BRANCH}\",
\"title\": \"${CI_COMMIT_REF_NAME}\",
\"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 branch
LISTMR=`curl --silent "${CI_PROJECT_URL}${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 one
if [ ${COUNTBRANCHES} -eq "0" ]; then
curl -X POST "${CI_PROJECT_URL}${CI_PROJECT_ID}/merge_requests" \
--header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" \
--header "Content-Type: application/json" \
--data "${BODY}";
echo "Opened a new merge request: ${CI_COMMIT_REF_NAME} and assigned to you";
exit;
fi
echo "No new merge request opened";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment