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."""
25
branch as _mod_branch,
30
from ...git.urls import git_url_to_bzr_url
31
from ...trace import mutter
32
from ...transport import get_transport
34
from ...propose import (
41
PrerequisiteBranchUnsupported,
46
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
47
DEFAULT_PAGE_SIZE = 50
50
def mp_status_to_status(status):
55
'closed': 'closed'}[status]
58
class NotGitLabUrl(errors.BzrError):
60
_fmt = "Not a GitLab URL: %(url)s"
62
def __init__(self, url):
63
errors.BzrError.__init__(self)
67
class NotMergeRequestUrl(errors.BzrError):
69
_fmt = "Not a merge proposal URL: %(url)s"
71
def __init__(self, host, url):
72
errors.BzrError.__init__(self)
77
class DifferentGitLabInstances(errors.BzrError):
79
_fmt = ("Can't create merge proposals across GitLab instances: "
80
"%(source_host)s and %(target_host)s")
82
def __init__(self, source_host, target_host):
83
self.source_host = source_host
84
self.target_host = target_host
87
class GitLabLoginMissing(errors.BzrError):
89
_fmt = ("Please log into GitLab")
92
class GitlabLoginError(errors.BzrError):
94
_fmt = ("Error logging in: %(error)s")
96
def __init__(self, error):
100
class GitLabConflict(errors.BzrError):
102
_fmt = "Conflict during operation: %(reason)s"
104
def __init__(self, reason):
105
errors.BzrError(self, reason=reason)
108
class ForkingDisabled(errors.BzrError):
110
_fmt = ("Forking on project %(project)s is disabled.")
112
def __init__(self, project):
113
self.project = project
116
class MergeRequestExists(Exception):
117
"""Raised when a merge requests already exists."""
120
def default_config_path():
121
return os.path.join(bedding.config_dir(), 'gitlab.conf')
124
def store_gitlab_token(name, url, private_token):
125
"""Store a GitLab token in a configuration file."""
127
config = configparser.ConfigParser()
128
path = default_config_path()
130
config.add_section(name)
131
config[name]['url'] = url
132
config[name]['private_token'] = private_token
133
with open(path, 'w') as f:
139
config = configparser.ConfigParser()
141
[os.path.expanduser(p) for p in _DEFAULT_FILES] +
142
[default_config_path()])
143
for name, section in config.items():
147
def get_credentials_by_url(url):
148
for name, credentials in iter_tokens():
149
if 'url' not in credentials:
151
if credentials['url'].rstrip('/') == url.rstrip('/'):
157
def parse_gitlab_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
if path.endswith('.git'):
170
def parse_gitlab_branch_url(branch):
171
url = urlutils.strip_segment_parameters(branch.user_url)
172
host, path = parse_gitlab_url(url)
173
return host, path, branch.name
176
def parse_gitlab_merge_request_url(url):
177
(scheme, user, password, host, port, path) = urlutils.parse_url(
179
if scheme not in ('git+ssh', 'https', 'http'):
180
raise NotGitLabUrl(url)
182
raise NotGitLabUrl(url)
183
path = path.strip('/')
184
parts = path.split('/')
186
raise NotMergeRequestUrl(host, url)
187
if parts[-2] != 'merge_requests':
188
raise NotMergeRequestUrl(host, url)
190
project_name = '/'.join(parts[:-3])
192
project_name = '/'.join(parts[:-2])
193
return host, project_name, int(parts[-1])
196
class GitLabMergeProposal(MergeProposal):
198
def __init__(self, gl, mr):
202
def _update(self, **kwargs):
203
self.gl._update_merge_request(self._mr['project_id'], self._mr['iid'], kwargs)
206
return "<%s at %r>" % (type(self).__name__, self._mr['web_url'])
210
return self._mr['web_url']
212
def get_description(self):
213
return self._mr['description']
215
def set_description(self, description):
216
self._update(description=description, title=determine_title(description))
218
def get_commit_message(self):
219
return self._mr.get('merge_commit_message')
221
def set_commit_message(self, message):
222
raise errors.UnsupportedOperation(self.set_commit_message, self)
224
def _branch_url_from_project(self, project_id, branch_name):
225
if project_id is None:
227
project = self.gl._get_project(project_id)
228
return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
230
def get_source_branch_url(self):
231
return self._branch_url_from_project(
232
self._mr['source_project_id'], self._mr['source_branch'])
234
def get_source_revision(self):
235
from breezy.git.mapping import default_mapping
236
sha = self._mr['sha']
239
return default_mapping.revision_id_foreign_to_bzr(sha.encode('ascii'))
241
def get_target_branch_url(self):
242
return self._branch_url_from_project(
243
self._mr['target_project_id'], self._mr['target_branch'])
245
def _get_project_name(self, project_id):
246
source_project = self.gl._get_project(project_id)
247
return source_project['path_with_namespace']
249
def get_source_project(self):
250
return self._get_project_name(self._mr['source_project_id'])
252
def get_target_project(self):
253
return self._get_project_name(self._mr['target_project_id'])
256
return (self._mr['state'] == 'merged')
259
return (self._mr['state'] == 'closed')
262
return self._update(state_event='reopen')
265
self._update(state_event='close')
267
def merge(self, commit_message=None):
268
# https://docs.gitlab.com/ee/api/merge_requests.html#accept-mr
269
self._mr.merge(merge_commit_message=commit_message)
271
def can_be_merged(self):
272
if self._mr['merge_status'] == 'cannot_be_merged':
274
elif self._mr['merge_status'] == 'can_be_merged':
276
elif self._mr['merge_status'] in (
277
'unchecked', 'cannot_be_merged_recheck'):
278
# See https://gitlab.com/gitlab-org/gitlab/-/commit/7517105303c for
279
# an explanation of the distinction between unchecked and
280
# cannot_be_merged_recheck
283
raise ValueError(self._mr['merge_status'])
285
def get_merged_by(self):
286
user = self._mr.get('merged_by')
289
return user['username']
291
def get_merged_at(self):
292
merged_at = self._mr.get('merged_at')
293
if merged_at is None:
296
return iso8601.parse_date(merged_at)
298
def post_comment(self, body):
299
kwargs = {'body': body}
300
self.gl._post_merge_request_note(
301
self._mr['project_id'], self._mr['iid'], kwargs)
304
def gitlab_url_to_bzr_url(url, name):
305
return git_url_to_bzr_url(url, branch=name)
308
class GitLab(Hoster):
309
"""GitLab hoster implementation."""
311
supports_merge_proposal_labels = True
312
supports_merge_proposal_commit_message = False
313
supports_allow_collaboration = True
314
merge_proposal_description_format = 'markdown'
317
return "<GitLab(%r)>" % self.base_url
321
return self.transport.base
324
def base_hostname(self):
325
return urlutils.parse_url(self.base_url)[3]
327
def _api_request(self, method, path, fields=None, body=None):
328
return self.transport.request(
329
method, urlutils.join(self.base_url, 'api', 'v4', path),
330
headers=self.headers, fields=fields, body=body)
332
def __init__(self, transport, private_token):
333
self.transport = transport
334
self.headers = {"Private-Token": private_token}
337
def _get_user(self, username):
338
path = 'users/%s' % urlutils.quote(str(username), '')
339
response = self._api_request('GET', path)
340
if response.status == 404:
341
raise KeyError('no such user %s' % username)
342
if response.status == 200:
343
return json.loads(response.data)
344
raise errors.UnexpectedHttpStatus(path, response.status)
346
def _get_user_by_email(self, email):
347
path = 'users?search=%s' % urlutils.quote(str(email), '')
348
response = self._api_request('GET', path)
349
if response.status == 404:
350
raise KeyError('no such user %s' % email)
351
if response.status == 200:
352
ret = json.loads(response.data)
354
raise ValueError('unexpected number of results; %r' % ret)
356
raise errors.UnexpectedHttpStatus(path, response.status)
358
def _get_project(self, project_name):
359
path = 'projects/%s' % urlutils.quote(str(project_name), '')
360
response = self._api_request('GET', path)
361
if response.status == 404:
362
raise NoSuchProject(project_name)
363
if response.status == 200:
364
return json.loads(response.data)
365
raise errors.UnexpectedHttpStatus(path, response.status)
367
def _fork_project(self, project_name, timeout=50, interval=5, owner=None):
368
path = 'projects/%s/fork' % urlutils.quote(str(project_name), '')
370
if owner is not None:
371
fields['namespace'] = owner
372
response = self._api_request('POST', path, fields=fields)
373
if response.status == 404:
374
raise ForkingDisabled(project_name)
375
if response.status == 409:
376
resp = json.loads(response.data)
377
raise GitLabConflict(resp.get('message'))
378
if response.status not in (200, 201):
379
raise errors.UnexpectedHttpStatus(path, response.status)
380
# The response should be valid JSON, but let's ignore it
381
project = json.loads(response.data)
382
# Spin and wait until import_status for new project
384
deadline = time.time() + timeout
385
while project['import_status'] not in ('finished', 'none'):
386
mutter('import status is %s', project['import_status'])
387
if time.time() > deadline:
388
raise Exception('timeout waiting for project to become available')
390
project = self._get_project(project['path_with_namespace'])
393
def get_current_user(self):
394
return self._current_user['username']
396
def get_user_url(self, username):
397
return urlutils.join(self.base_url, username)
399
def _list_paged(self, path, parameters=None, per_page=None):
400
if parameters is None:
403
parameters = dict(parameters.items())
405
parameters['per_page'] = str(per_page)
408
parameters['page'] = page
409
response = self._api_request(
411
';'.join(['%s=%s' % item for item in parameters.items()]))
412
if response.status == 403:
413
raise errors.PermissionDenied(response.text)
414
if response.status != 200:
415
raise errors.UnexpectedHttpStatus(path, response.status)
416
page = response.getheader("X-Next-Page")
417
for entry in json.loads(response.data):
420
def _list_merge_requests(self, owner=None, project=None, state=None):
421
if project is not None:
422
path = 'projects/%s/merge_requests' % urlutils.quote(str(project), '')
424
path = 'merge_requests'
427
parameters['state'] = state
429
parameters['owner_id'] = urlutils.quote(owner, '')
430
return self._list_paged(path, parameters, per_page=DEFAULT_PAGE_SIZE)
432
def _get_merge_request(self, project, merge_id):
433
path = 'projects/%s/merge_requests/%d' % (urlutils.quote(str(project), ''), merge_id)
434
response = self._api_request('GET', path)
435
if response.status == 403:
436
raise errors.PermissionDenied(response.text)
437
if response.status != 200:
438
raise errors.UnexpectedHttpStatus(path, response.status)
439
return json.loads(response.data)
441
def _list_projects(self, owner):
442
path = 'users/%s/projects' % urlutils.quote(str(owner), '')
444
return self._list_paged(path, parameters, per_page=DEFAULT_PAGE_SIZE)
446
def _update_merge_request(self, project_id, iid, mr):
447
path = 'projects/%s/merge_requests/%s' % (
448
urlutils.quote(str(project_id), ''), iid)
449
response = self._api_request('PUT', path, fields=mr)
450
if response.status == 200:
451
return json.loads(response.data)
452
raise errors.UnexpectedHttpStatus(path, response.status)
454
def _post_merge_request_note(self, project_id, iid, kwargs):
455
path = 'projects/%s/merge_requests/%s/notes' % (
456
urlutils.quote(str(project_id), ''), iid)
457
response = self._api_request('POST', path, fields=kwargs)
458
if response.status == 201:
459
json.loads(response.data)
461
raise errors.UnexpectedHttpStatus(path, response.status)
463
def _create_mergerequest(
464
self, title, source_project_id, target_project_id,
465
source_branch_name, target_branch_name, description,
466
labels=None, allow_collaboration=False):
467
path = 'projects/%s/merge_requests' % source_project_id
470
'source_branch': source_branch_name,
471
'target_branch': target_branch_name,
472
'target_project_id': target_project_id,
473
'description': description,
474
'allow_collaboration': allow_collaboration,
477
fields['labels'] = labels
478
response = self._api_request('POST', path, fields=fields)
479
if response.status == 403:
480
raise errors.PermissionDenied(response.text)
481
if response.status == 409:
482
raise MergeRequestExists()
483
if response.status != 201:
484
raise errors.UnexpectedHttpStatus(path, response.status)
485
return json.loads(response.data)
487
def get_push_url(self, branch):
488
(host, project_name, branch_name) = parse_gitlab_branch_url(branch)
489
project = self._get_project(project_name)
490
return gitlab_url_to_bzr_url(
491
project['ssh_url_to_repo'], branch_name)
493
def publish_derived(self, local_branch, base_branch, name, project=None,
494
owner=None, revision_id=None, overwrite=False,
495
allow_lossy=True, tag_selector=None):
496
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
498
owner = self.get_current_user()
500
project = self._get_project(base_project)['path']
502
target_project = self._get_project('%s/%s' % (owner, project))
503
except NoSuchProject:
504
target_project = self._fork_project(base_project, owner=owner)
505
remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
506
remote_dir = controldir.ControlDir.open(remote_repo_url)
508
push_result = remote_dir.push_branch(
509
local_branch, revision_id=revision_id, overwrite=overwrite,
510
name=name, tag_selector=tag_selector)
511
except errors.NoRoundtrippingSupport:
514
push_result = remote_dir.push_branch(
515
local_branch, revision_id=revision_id, overwrite=overwrite,
516
name=name, lossy=True, tag_selector=tag_selector)
517
public_url = gitlab_url_to_bzr_url(
518
target_project['http_url_to_repo'], name)
519
return push_result.target_branch, public_url
521
def get_derived_branch(self, base_branch, name, project=None, owner=None):
522
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
524
owner = self.get_current_user()
526
project = self._get_project(base_project)['path']
528
target_project = self._get_project('%s/%s' % (owner, project))
529
except NoSuchProject:
530
raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
531
return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
532
target_project['ssh_url_to_repo'], name))
534
def get_proposer(self, source_branch, target_branch):
535
return GitlabMergeProposalBuilder(self, source_branch, target_branch)
537
def iter_proposals(self, source_branch, target_branch, status):
538
(source_host, source_project_name, source_branch_name) = (
539
parse_gitlab_branch_url(source_branch))
540
(target_host, target_project_name, target_branch_name) = (
541
parse_gitlab_branch_url(target_branch))
542
if source_host != target_host:
543
raise DifferentGitLabInstances(source_host, target_host)
544
source_project = self._get_project(source_project_name)
545
target_project = self._get_project(target_project_name)
546
state = mp_status_to_status(status)
547
for mr in self._list_merge_requests(
548
project=target_project['id'], state=state):
549
if (mr['source_project_id'] != source_project['id'] or
550
mr['source_branch'] != source_branch_name or
551
mr['target_project_id'] != target_project['id'] or
552
mr['target_branch'] != target_branch_name):
554
yield GitLabMergeProposal(self, mr)
556
def hosts(self, branch):
558
(host, project, branch_name) = parse_gitlab_branch_url(branch)
561
return self.base_hostname == host
564
response = self._api_request('GET', 'user')
565
if response.status == 200:
566
self._current_user = json.loads(response.data)
569
if json.loads(response.data) == {"message": "401 Unauthorized"}:
570
raise GitLabLoginMissing()
572
raise GitlabLoginError(response.text)
573
raise UnsupportedHoster(self.base_url)
576
def probe_from_url(cls, url, possible_transports=None):
578
(host, project) = parse_gitlab_url(url)
580
raise UnsupportedHoster(url)
581
transport = get_transport(
582
'https://%s' % host, possible_transports=possible_transports)
583
credentials = get_credentials_by_url(transport.base)
584
if credentials is not None:
585
return cls(transport, credentials.get('private_token'))
586
raise UnsupportedHoster(url)
589
def iter_instances(cls):
590
for name, credentials in iter_tokens():
591
if 'url' not in credentials:
594
get_transport(credentials['url']),
595
private_token=credentials.get('private_token'))
597
def iter_my_proposals(self, status='open'):
598
state = mp_status_to_status(status)
599
for mp in self._list_merge_requests(
600
owner=self.get_current_user(), state=state):
601
yield GitLabMergeProposal(self, mp)
603
def iter_my_forks(self):
604
for project in self._list_projects(owner=self.get_current_user()):
605
base_project = project.get('forked_from_project')
608
yield project['path_with_namespace']
610
def get_proposal_by_url(self, url):
612
(host, project, merge_id) = parse_gitlab_merge_request_url(url)
614
raise UnsupportedHoster(url)
615
except NotMergeRequestUrl as e:
616
if self.base_hostname == e.host:
619
raise UnsupportedHoster(url)
620
if self.base_hostname != host:
621
raise UnsupportedHoster(url)
622
project = self._get_project(project)
623
mr = self._get_merge_request(project['path_with_namespace'], merge_id)
624
return GitLabMergeProposal(self, mr)
626
def delete_project(self, project):
627
path = 'projects/%s' % urlutils.quote(str(project), '')
628
response = self._api_request('DELETE', path)
629
if response.status == 404:
630
raise NoSuchProject(project)
631
if response.status != 202:
632
raise errors.UnexpectedHttpStatus(path, response.status)
635
class GitlabMergeProposalBuilder(MergeProposalBuilder):
637
def __init__(self, gl, source_branch, target_branch):
639
self.source_branch = source_branch
640
(self.source_host, self.source_project_name, self.source_branch_name) = (
641
parse_gitlab_branch_url(source_branch))
642
self.target_branch = target_branch
643
(self.target_host, self.target_project_name, self.target_branch_name) = (
644
parse_gitlab_branch_url(target_branch))
645
if self.source_host != self.target_host:
646
raise DifferentGitLabInstances(self.source_host, self.target_host)
648
def get_infotext(self):
649
"""Determine the initial comment for the merge proposal."""
651
info.append("Gitlab instance: %s\n" % self.target_host)
652
info.append("Source: %s\n" % self.source_branch.user_url)
653
info.append("Target: %s\n" % self.target_branch.user_url)
656
def get_initial_body(self):
657
"""Get a body for the proposal for the user to modify.
659
:return: a str or None.
663
def create_proposal(self, description, reviewers=None, labels=None,
664
prerequisite_branch=None, commit_message=None,
665
work_in_progress=False, allow_collaboration=False):
666
"""Perform the submission."""
667
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
668
if prerequisite_branch is not None:
669
raise PrerequisiteBranchUnsupported(self)
670
# Note that commit_message is ignored, since Gitlab doesn't support it.
671
source_project = self.gl._get_project(self.source_project_name)
672
target_project = self.gl._get_project(self.target_project_name)
673
# TODO(jelmer): Allow setting title explicitly
674
title = determine_title(description)
676
title = 'WIP: %s' % title
677
# TODO(jelmer): Allow setting milestone field
678
# TODO(jelmer): Allow setting squash field
681
'source_project_id': source_project['id'],
682
'target_project_id': target_project['id'],
683
'source_branch_name': self.source_branch_name,
684
'target_branch_name': self.target_branch_name,
685
'description': description,
686
'allow_collaboration': allow_collaboration}
688
kwargs['labels'] = ','.join(labels)
690
kwargs['assignee_ids'] = []
691
for reviewer in reviewers:
693
user = self.gl._get_user_by_email(reviewer)
695
user = self.gl._get_user(reviewer)
696
kwargs['assignee_ids'].append(user['id'])
698
merge_request = self.gl._create_mergerequest(**kwargs)
699
except MergeRequestExists:
700
raise MergeProposalExists(self.source_branch.user_url)
701
return GitLabMergeProposal(self.gl, merge_request)
704
def register_gitlab_instance(shortname, url):
705
"""Register a gitlab instance.
707
:param shortname: Short name (e.g. "gitlab")
708
:param url: URL to the gitlab instance
710
from breezy.bugtracker import (
712
ProjectIntegerBugTracker,
714
tracker_registry.register(
715
shortname, ProjectIntegerBugTracker(
716
shortname, url + '/{project}/issues/{id}'))