Thursday, May 19, 2016

Changing merge request target branch in gitlab

Yes, it's possible with API usage.
There is even a script that chamges target branch with minimal configuration.

Gitlab is increasingly popular alternative for Github, commonly used by corporations that are able to save monthly fee for Github. It's open source project and front end and its usability seems to be still behind commercial and successful predecessor.
In my opinion Merge Requests are functionality that is exceptionally affected by suboptimal design. You just need to get used to it and train yourself not to click big green 'Click me' button, which causes MR to be merged. And changing the target branch of merge request seems to be impossible.
Thanks to careful readers among my colleagues, I have found out that this option exists, however only way to do it is to use Gitlab API. The API (similarly to Jenkins) utilizes concept of private token. It is a secret that allows a user to authenticate using unique token instead standard username and password. Maybe it is not most secure way, but certainly that is easy and convenient. Each HTTP request to Gitlab API that is performed in some user context, must contain that private token. It may be sent as a header or url parameter. Depending on your deployment configurationone of that ways may or may not be disabled ;> Url parameter worked for me quite well.
To edit a Merge Request we need to know project it relates to, as well as MR identifier, which is not same as visible in GUI (that one is referred to as iid, unique in project scope).
Operation will take 3 HTTP calls. First is ment to retrieve project id by its name.
GET /projects/search/:name_to_find
I assume there are no more than one projects found by given name.
Second will convert id from GUI to MR id.
GET /projects/:id/merge_requests?iid=42
or you can select manually from all opened MRs.
GET /projects/:id/merge_requests?state=opened
Knowing project id and MR id we can now update target branch by sending simple json object carrying new target branch as a value.
PUT /projects/:id/merge_request/:merge_request_id
{ "target_branch": "the_target_br" }
In my case I had to remove plural form `s` from merge_requests in url (that was different from API documentation, but I assume it's change in some other version of Gitlab). I was happy this option was possible, however I must admit I had to write the script to make the changing user friendly.