1
# Copyright (C) 2018 Breezy Developers
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Support for GitLab."""
19
from __future__ import absolute_import
27
branch as _mod_branch,
32
from ...git.urls import git_url_to_bzr_url
33
from ...sixish import PY3
34
from ...trace import mutter
35
from ...transport import get_transport
37
from .propose import (
43
PrerequisiteBranchUnsupported,
48
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
51
def mp_status_to_status(status):
56
'closed': 'closed'}[status]
59
class NotGitLabUrl(errors.BzrError):
61
_fmt = "Not a GitLab URL: %(url)s"
63
def __init__(self, url):
64
errors.BzrError.__init__(self)
68
class NotMergeRequestUrl(errors.BzrError):
70
_fmt = "Not a merge proposal URL: %(url)s"
72
def __init__(self, host, url):
73
errors.BzrError.__init__(self)
78
class DifferentGitLabInstances(errors.BzrError):
80
_fmt = ("Can't create merge proposals across GitLab instances: "
81
"%(source_host)s and %(target_host)s")
83
def __init__(self, source_host, target_host):
84
self.source_host = source_host
85
self.target_host = target_host
88
class GitLabLoginMissing(errors.BzrError):
90
_fmt = ("Please log into GitLab")
93
class GitlabLoginError(errors.BzrError):
95
_fmt = ("Error logging in: %(error)s")
97
def __init__(self, error):
101
def default_config_path():
102
return os.path.join(bedding.config_dir(), 'gitlab.conf')
105
def store_gitlab_token(name, url, private_token):
106
"""Store a GitLab token in a configuration file."""
108
config = configparser.ConfigParser()
109
path = default_config_path()
111
config.add_section(name)
112
config[name]['url'] = url
113
config[name]['private_token'] = private_token
114
with open(path, 'w') as f:
120
config = configparser.ConfigParser()
122
[os.path.expanduser(p) for p in _DEFAULT_FILES] +
123
[default_config_path()])
124
for name, section in config.items():
128
def get_credentials_by_url(url):
129
for name, credentials in iter_tokens():
130
if 'url' not in credentials:
132
if credentials['url'].rstrip('/') == url.rstrip('/'):
138
def parse_gitlab_url(url):
139
(scheme, user, password, host, port, path) = urlutils.parse_url(
141
if scheme not in ('git+ssh', 'https', 'http'):
142
raise NotGitLabUrl(url)
144
raise NotGitLabUrl(url)
145
path = path.strip('/')
146
if path.endswith('.git'):
151
def parse_gitlab_branch_url(branch):
152
url = urlutils.split_segment_parameters(branch.user_url)[0]
153
host, path = parse_gitlab_url(url)
154
return host, path, branch.name
157
def parse_gitlab_merge_request_url(url):
158
(scheme, user, password, host, port, path) = urlutils.parse_url(
160
if scheme not in ('git+ssh', 'https', 'http'):
161
raise NotGitLabUrl(url)
163
raise NotGitLabUrl(url)
164
path = path.strip('/')
165
parts = path.split('/')
166
if parts[-2] != 'merge_requests':
167
raise NotMergeRequestUrl(host, url)
168
return host, '/'.join(parts[:-2]), int(parts[-1])
171
class GitLabMergeProposal(MergeProposal):
173
def __init__(self, gl, mr):
177
def _update(self, **kwargs):
178
self.gl._update_merge_request(self._mr['project_id'], self._mr['iid'], kwargs)
182
return self._mr['web_url']
184
def get_description(self):
185
return self._mr['description']
187
def set_description(self, description):
188
self._update(description=description, title=description.splitlines()[0])
190
def get_commit_message(self):
191
return self._mr.get('merge_commit_message')
193
def set_commit_message(self, message):
194
raise errors.UnsupportedOperation(self.set_commit_message, self)
196
def _branch_url_from_project(self, project_id, branch_name):
197
if project_id is None:
199
project = self.gl._get_project(project_id)
200
return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
202
def get_source_branch_url(self):
203
return self._branch_url_from_project(
204
self._mr['source_project_id'], self._mr['source_branch'])
206
def get_target_branch_url(self):
207
return self._branch_url_from_project(
208
self._mr['target_project_id'], self._mr['target_branch'])
211
return (self._mr['state'] == 'merged')
214
self._update(state_event='close')
216
def merge(self, commit_message=None):
217
# https://docs.gitlab.com/ee/api/merge_requests.html#accept-mr
218
self._mr.merge(merge_commit_message=commit_message)
220
def can_be_merged(self):
221
if self._mr['merge_status'] == 'cannot_be_merged':
223
elif self._mr['merge_status'] == 'can_be_merged':
226
raise ValueError(self._mr['merge_status'])
229
def gitlab_url_to_bzr_url(url, name):
231
name = name.encode('utf-8')
232
return urlutils.join_segment_parameters(
233
git_url_to_bzr_url(url), {"branch": name})
236
class GitLab(Hoster):
237
"""GitLab hoster implementation."""
239
supports_merge_proposal_labels = True
240
supports_merge_proposal_commit_message = False
243
return "<GitLab(%r)>" % self.base_url
247
return self.transport.base
249
def _api_request(self, method, path, fields=None):
250
return self.transport.request(
251
method, urlutils.join(self.base_url, 'api', 'v4', path),
252
headers=self.headers, fields=fields)
254
def __init__(self, transport, private_token):
255
self.transport = transport
256
self.headers = {"Private-Token": private_token}
259
def _get_project(self, project_name):
260
path = 'projects/%s' % urlutils.quote(str(project_name), '')
261
response = self._api_request('GET', path)
262
if response.status == 404:
263
raise NoSuchProject(project_name)
264
if response.status == 200:
265
return json.loads(response.data)
266
raise errors.InvalidHttpResponse(path, response.text)
268
def _fork_project(self, project_name, timeout=50, interval=5):
269
path = 'projects/%s/fork' % urlutils.quote(str(project_name), '')
270
response = self._api_request('POST', path)
271
if response.status not in (200, 201):
272
raise errors.InvalidHttpResponse(path, response.text)
273
# The response should be valid JSON, but let's ignore it
274
json.loads(response.data)
275
# Spin and wait until import_status for new project
277
deadline = time.time() + timeout
279
project = self._get_project(project_name)
280
if project['import_status'] in ('finished', 'none'):
282
mutter('import status is %s', project['import_status'])
283
if time.time() > deadline:
284
raise Exception('timeout waiting for project to become available')
287
def _get_logged_in_username(self):
288
return self._current_user['username']
290
def _list_merge_requests(self, owner=None, project=None, state=None):
291
if project is not None:
292
path = 'projects/%s/merge_requests' % urlutils.quote(str(project), '')
294
path = 'merge_requests'
297
parameters['state'] = state
299
parameters['owner_id'] = urlutils.quote(owner, '')
300
response = self._api_request(
302
';'.join(['%s=%s' % item for item in parameters.items()]))
303
if response.status == 403:
304
raise errors.PermissionDenied(response.text)
305
if response.status == 200:
306
return json.loads(response.data)
307
raise errors.InvalidHttpResponse(path, response.text)
309
def _update_merge_request(self, project_id, iid, mr):
310
path = 'projects/%s/merge_requests/%s' % (
311
urlutils.quote(str(project_id), ''), iid)
312
response = self._api_request('PUT', path, fields=mr)
313
if response.status == 200:
314
return json.loads(response.data)
315
raise errors.InvalidHttpResponse(path, response.text)
317
def _create_mergerequest(
318
self, title, source_project_id, target_project_id,
319
source_branch_name, target_branch_name, description,
321
path = 'projects/%s/merge_requests' % source_project_id
324
'source_branch': source_branch_name,
325
'target_branch': target_branch_name,
326
'target_project_id': target_project_id,
327
'description': description,
330
fields['labels'] = labels
331
response = self._api_request('POST', path, fields=fields)
332
if response.status == 403:
333
raise errors.PermissionDenied(response.text)
334
if response.status == 409:
335
raise MergeProposalExists(self.source_branch.user_url)
336
if response.status != 201:
337
raise errors.InvalidHttpResponse(path, response.text)
338
return json.loads(response.data)
340
def get_push_url(self, branch):
341
(host, project_name, branch_name) = parse_gitlab_branch_url(branch)
342
project = self._get_project(project_name)
343
return gitlab_url_to_bzr_url(
344
project['ssh_url_to_repo'], branch_name)
346
def publish_derived(self, local_branch, base_branch, name, project=None,
347
owner=None, revision_id=None, overwrite=False,
349
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
351
owner = self._get_logged_in_username()
353
project = self._get_project(base_project)['path']
355
target_project = self._get_project('%s/%s' % (owner, project))
356
except NoSuchProject:
357
target_project = self._fork_project(base_project)
358
remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
359
remote_dir = controldir.ControlDir.open(remote_repo_url)
361
push_result = remote_dir.push_branch(
362
local_branch, revision_id=revision_id, overwrite=overwrite,
364
except errors.NoRoundtrippingSupport:
367
push_result = remote_dir.push_branch(
368
local_branch, revision_id=revision_id, overwrite=overwrite,
369
name=name, lossy=True)
370
public_url = gitlab_url_to_bzr_url(
371
target_project['http_url_to_repo'], name)
372
return push_result.target_branch, public_url
374
def get_derived_branch(self, base_branch, name, project=None, owner=None):
375
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
377
owner = self._get_logged_in_username()
379
project = self._get_project(base_project)['path']
381
target_project = self._get_project('%s/%s' % (owner, project))
382
except NoSuchProject:
383
raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
384
return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
385
target_project['ssh_url_to_repo'], name))
387
def get_proposer(self, source_branch, target_branch):
388
return GitlabMergeProposalBuilder(self, source_branch, target_branch)
390
def iter_proposals(self, source_branch, target_branch, status):
391
(source_host, source_project_name, source_branch_name) = (
392
parse_gitlab_branch_url(source_branch))
393
(target_host, target_project_name, target_branch_name) = (
394
parse_gitlab_branch_url(target_branch))
395
if source_host != target_host:
396
raise DifferentGitLabInstances(source_host, target_host)
397
source_project = self._get_project(source_project_name)
398
target_project = self._get_project(target_project_name)
399
state = mp_status_to_status(status)
400
for mr in self._list_merge_requests(
401
project=target_project['id'], state=state):
402
if (mr['source_project_id'] != source_project['id'] or
403
mr['source_branch'] != source_branch_name or
404
mr['target_project_id'] != target_project['id'] or
405
mr['target_branch'] != target_branch_name):
407
yield GitLabMergeProposal(self, mr)
409
def hosts(self, branch):
411
(host, project, branch_name) = parse_gitlab_branch_url(branch)
414
return (self.base_url == ('https://%s' % host))
417
response = self._api_request('GET', 'user')
418
if response.status == 200:
419
self._current_user = json.loads(response.data)
422
if json.loads(response.data) == {"message": "401 Unauthorized"}:
423
raise GitLabLoginMissing()
425
raise GitlabLoginError(response.text)
426
raise UnsupportedHoster(url)
429
def probe_from_url(cls, url, possible_transports=None):
431
(host, project) = parse_gitlab_url(url)
433
raise UnsupportedHoster(url)
434
transport = get_transport(
435
'https://%s' % host, possible_transports=possible_transports)
436
credentials = get_credentials_by_url(transport.base)
437
if credentials is not None:
438
return cls(transport, credentials.get('private_token'))
439
raise UnsupportedHoster(url)
442
def iter_instances(cls):
443
for name, credentials in iter_tokens():
444
if 'url' not in credentials:
447
get_transport(credentials['url']),
448
private_token=credentials.get('private_token'))
450
def iter_my_proposals(self, status='open'):
451
state = mp_status_to_status(status)
452
for mp in self._list_merge_requests(
453
owner=self._get_logged_in_username(), state=state):
454
yield GitLabMergeProposal(self, mp)
456
def get_proposal_by_url(self, url):
458
(host, project, merge_id) = parse_gitlab_merge_request_url(url)
460
raise UnsupportedHoster(url)
461
except NotMergeRequestUrl as e:
462
if self.base_url == ('https://%s' % e.host):
465
raise UnsupportedHoster(url)
466
if self.base_url != ('https://%s' % host):
467
raise UnsupportedHoster(url)
468
project = self._get_project(project)
469
mr = project.mergerequests.get(merge_id)
470
return GitLabMergeProposal(mr)
473
class GitlabMergeProposalBuilder(MergeProposalBuilder):
475
def __init__(self, gl, source_branch, target_branch):
477
self.source_branch = source_branch
478
(self.source_host, self.source_project_name, self.source_branch_name) = (
479
parse_gitlab_branch_url(source_branch))
480
self.target_branch = target_branch
481
(self.target_host, self.target_project_name, self.target_branch_name) = (
482
parse_gitlab_branch_url(target_branch))
483
if self.source_host != self.target_host:
484
raise DifferentGitLabInstances(self.source_host, self.target_host)
486
def get_infotext(self):
487
"""Determine the initial comment for the merge proposal."""
489
info.append("Gitlab instance: %s\n" % self.target_host)
490
info.append("Source: %s\n" % self.source_branch.user_url)
491
info.append("Target: %s\n" % self.target_branch.user_url)
494
def get_initial_body(self):
495
"""Get a body for the proposal for the user to modify.
497
:return: a str or None.
501
def create_proposal(self, description, reviewers=None, labels=None,
502
prerequisite_branch=None, commit_message=None):
503
"""Perform the submission."""
504
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
505
if prerequisite_branch is not None:
506
raise PrerequisiteBranchUnsupported(self)
507
# Note that commit_message is ignored, since Gitlab doesn't support it.
508
# TODO(jelmer): Support reviewers
509
source_project = self.gl._get_project(self.source_project_name)
510
target_project = self.gl._get_project(self.target_project_name)
511
# TODO(jelmer): Allow setting title explicitly
512
title = description.splitlines()[0]
513
# TODO(jelmer): Allow setting allow_collaboration field
514
# TODO(jelmer): Allow setting milestone field
515
# TODO(jelmer): Allow setting squash field
518
'source_project_id': source_project['id'],
519
'target_project_id': target_project['id'],
520
'source_branch_name': self.source_branch_name,
521
'target_branch_name': self.target_branch_name,
522
'description': description}
524
kwargs['labels'] = ','.join(labels)
525
merge_request = self.gl._create_mergerequest(**kwargs)
526
return GitLabMergeProposal(self.gl, merge_request)
529
def register_gitlab_instance(shortname, url):
530
"""Register a gitlab instance.
532
:param shortname: Short name (e.g. "gitlab")
533
:param url: URL to the gitlab instance
535
from breezy.bugtracker import (
537
ProjectIntegerBugTracker,
539
tracker_registry.register(
540
shortname, ProjectIntegerBugTracker(
541
shortname, url + '/{project}/issues/{id}'))