Creating a Gitlab Merge Request from the Command Line

I quite like working with Merge Requests for Code Reviews and for providing a Feature Changelog.

Additionally, I tend to create them quite early. Sometimes even when creating a new branch.

This allows me to assign other people who might be interested on the progress of the Feature I’m working on.

Neatly, Gitlab already shows you a Link when pushing to a branch.

This URL creates a MR for the branch feature/my-branch.

Another way is using Git Push Options.

Gitlab Push Options

When pushing a commit to your Gitlab repository, you can specify some useful options. Note that this only passes variables to branch pipelines and not merge request pipelines.

# skip pipeline upon push
git push -o ci.skip
# add ci variables to pipeline
git push -o ci.variable="DEPLOY=QA"
# create a new MR from this branch
git push -o merge_request.create
# set MR assigne
git push -o merge_request.assign="<user>"

See Push options | GitLab

Additionally, for the case of already having pushed, I created a script to create the MR.

Shell Script to Create a Gitlab MR for the Current Branch

What it does:

  • Gets the URL of the repository with git remote get-url origin
  • Get the current branch name with git rev-parse --abbrev-ref HEAD
  • Encodes it properly, using my script.
  • Generates the correct Gitlab URL to create the MR
  • Opens the link with xdg-open
# USAGE: Create a new Merge Request to master for the current branch
GIT_REMOTE=$(git remote get-url origin)
    # convert ssh urls to https
    sed 's#^\(.*\).git#\1#g' |
    # remove .git suffix
    sed 's#.git$##g'
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
# open the url
xdg-open "${GITLAB_URL}/-/merge_requests/new?${OPT_SOURCE_BRANCH}"

Here’s the version I currently use.