Skip to content

Instantly share code, notes, and snippets.

@enVolt
Created August 30, 2019 05:56
Show Gist options
  • Save enVolt/3e14e5ebc46e19acdbc50b9c191571f1 to your computer and use it in GitHub Desktop.
Save enVolt/3e14e5ebc46e19acdbc50b9c191571f1 to your computer and use it in GitHub Desktop.
Create GitLab Merge Request from CLI

Create GitLab Merge Request from CLI

Since GitLab didn't have any CLI tool similar to GitHub (hub), I find it a very cumbersome task to raise a GitLab Merge Request to develop branch. Though GitLab automatically returns a URL which can be used to create a Merge Request, by default it proceed with master branch (or whatever is your default branch)

I created this small python script, which uses the GitLab APIs to generate a Merge Request, where the Target Branch for Merge Request can be passed as an argument.

Origin is extracted from the Git remote URL. This works fine if you're using SSH based URL, else modify the logic on Line #9.

Title is the last commit message

Target Branch defaults to master, which can be passed as first parameter to override. (createMergeRequests.py develop)

Source Branch is current branch, which can be passed as second parameter to override. (createMergeRequests.py develop master)

For quick use, I've placed the script in home directory, so it's can be accessed with ~/createMergeRequest.py. Make file executable, and replace the Line #1 with your python3 bin path.

#! /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
import os
import requests
import sys
GITLAB_TOKEN = "ABCD"
origin = os.popen('git remote get-url --push origin').read().strip()[15:][:-4]
source_branch = os.popen('git rev-parse --abbrev-ref HEAD').read().strip()
title = os.popen('git log -1 --pretty=%B').read().strip()
target_branch = "master"
if len(sys.argv) == 2:
target_branch = sys.argv[1]
if len(sys.argv) == 3:
source_branch = sys.argv[2]
print ("https://gitlab.com/api/v4/projects/" + origin.replace("/","%2F") + "/merge_requests")
res = requests.post("https://gitlab.com/api/v4/projects/" + origin.replace("/","%2F") + "/merge_requests", headers={"private-token": GITLAB_TOKEN}, json={
"target_branch": target_branch, "source_branch":source_branch, "title": title})
print (res.json()["web_url"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment