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']
49
DEFAULT_PAGE_SIZE = 50
52
def mp_status_to_status(status):
57
'closed': 'closed'}[status]
60
class NotGitLabUrl(errors.BzrError):
62
_fmt = "Not a GitLab URL: %(url)s"
64
def __init__(self, url):
65
errors.BzrError.__init__(self)
69
class NotMergeRequestUrl(errors.BzrError):
71
_fmt = "Not a merge proposal URL: %(url)s"
73
def __init__(self, host, url):
74
errors.BzrError.__init__(self)
79
class DifferentGitLabInstances(errors.BzrError):
81
_fmt = ("Can't create merge proposals across GitLab instances: "
82
"%(source_host)s and %(target_host)s")
84
def __init__(self, source_host, target_host):
85
self.source_host = source_host
86
self.target_host = target_host
89
class GitLabLoginMissing(errors.BzrError):
91
_fmt = ("Please log into GitLab")
94
class GitlabLoginError(errors.BzrError):
96
_fmt = ("Error logging in: %(error)s")
98
def __init__(self, error):
102
def default_config_path():
103
return os.path.join(bedding.config_dir(), 'gitlab.conf')
106
def store_gitlab_token(name, url, private_token):
107
"""Store a GitLab token in a configuration file."""
109
config = configparser.ConfigParser()
110
path = default_config_path()
112
config.add_section(name)
113
config[name]['url'] = url
114
config[name]['private_token'] = private_token
115
with open(path, 'w') as f:
121
config = configparser.ConfigParser()
123
[os.path.expanduser(p) for p in _DEFAULT_FILES] +
124
[default_config_path()])
125
for name, section in config.items():
129
def get_credentials_by_url(url):
130
for name, credentials in iter_tokens():
131
if 'url' not in credentials:
133
if credentials['url'].rstrip('/') == url.rstrip('/'):
139
def parse_gitlab_url(url):
140
(scheme, user, password, host, port, path) = urlutils.parse_url(
142
if scheme not in ('git+ssh', 'https', 'http'):
143
raise NotGitLabUrl(url)
145
raise NotGitLabUrl(url)
146
path = path.strip('/')
147
if path.endswith('.git'):
152
def parse_gitlab_branch_url(branch):
153
url = urlutils.split_segment_parameters(branch.user_url)[0]
154
host, path = parse_gitlab_url(url)
155
return host, path, branch.name
158
def parse_gitlab_merge_request_url(url):
159
(scheme, user, password, host, port, path) = urlutils.parse_url(
161
if scheme not in ('git+ssh', 'https', 'http'):
162
raise NotGitLabUrl(url)
164
raise NotGitLabUrl(url)
165
path = path.strip('/')
166
parts = path.split('/')
167
if parts[-2] != 'merge_requests':
168
raise NotMergeRequestUrl(host, url)
169
return host, '/'.join(parts[:-2]), int(parts[-1])
172
class GitLabMergeProposal(MergeProposal):
174
def __init__(self, gl, mr):
178
def _update(self, **kwargs):
179
self.gl._update_merge_request(self._mr['project_id'], self._mr['iid'], kwargs)
182
return "<%s at %r>" % (type(self).__name__, self._mr['web_url'])
186
return self._mr['web_url']
188
def get_description(self):
189
return self._mr['description']
191
def set_description(self, description):
192
self._update(description=description, title=description.splitlines()[0])
194
def get_commit_message(self):
195
return self._mr.get('merge_commit_message')
197
def set_commit_message(self, message):
198
raise errors.UnsupportedOperation(self.set_commit_message, self)
200
def _branch_url_from_project(self, project_id, branch_name):
201
if project_id is None:
203
project = self.gl._get_project(project_id)
204
return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
206
def get_source_branch_url(self):
207
return self._branch_url_from_project(
208
self._mr['source_project_id'], self._mr['source_branch'])
210
def get_target_branch_url(self):
211
return self._branch_url_from_project(
212
self._mr['target_project_id'], self._mr['target_branch'])
215
return (self._mr['state'] == 'merged')
218
return (self._mr['state'] == 'closed')
221
return self._update(state_event='open')
224
self._update(state_event='close')
226
def merge(self, commit_message=None):
227
# https://docs.gitlab.com/ee/api/merge_requests.html#accept-mr
228
self._mr.merge(merge_commit_message=commit_message)
230
def can_be_merged(self):
231
if self._mr['merge_status'] == 'cannot_be_merged':
233
elif self._mr['merge_status'] == 'can_be_merged':
236
raise ValueError(self._mr['merge_status'])
239
def gitlab_url_to_bzr_url(url, name):
241
name = name.encode('utf-8')
242
return git_url_to_bzr_url(url, branch=name)
245
class GitLab(Hoster):
246
"""GitLab hoster implementation."""
248
supports_merge_proposal_labels = True
249
supports_merge_proposal_commit_message = False
252
return "<GitLab(%r)>" % self.base_url
256
return self.transport.base
258
def _api_request(self, method, path, fields=None):
259
return self.transport.request(
260
method, urlutils.join(self.base_url, 'api', 'v4', path),
261
headers=self.headers, fields=fields)
263
def __init__(self, transport, private_token):
264
self.transport = transport
265
self.headers = {"Private-Token": private_token}
268
def _get_user(self, username):
269
path = 'users/%s' % urlutils.quote(str(project_name), '')
270
response = self._api_request('GET', path)
271
if response.status == 404:
272
raise KeyError('no such user %s' % username)
273
if response.status == 200:
274
return json.loads(response.data)
275
raise errors.InvalidHttpResponse(path, response.text)
277
def _get_user_by_email(self, username):
278
path = 'users?search=%s' % urlutils.quote(str(project_name), '')
279
response = self._api_request('GET', path)
280
if response.status == 404:
281
raise KeyError('no such user %s' % username)
282
if response.status == 200:
283
ret = json.loads(response.data)
285
raise ValueError('unexpected number of results; %r' % ret)
287
raise errors.InvalidHttpResponse(path, response.text)
289
def _get_project(self, project_name):
290
path = 'projects/%s' % urlutils.quote(str(project_name), '')
291
response = self._api_request('GET', path)
292
if response.status == 404:
293
raise NoSuchProject(project_name)
294
if response.status == 200:
295
return json.loads(response.data)
296
raise errors.InvalidHttpResponse(path, response.text)
298
def _fork_project(self, project_name, timeout=50, interval=5):
299
path = 'projects/%s/fork' % urlutils.quote(str(project_name), '')
300
response = self._api_request('POST', path)
301
if response.status not in (200, 201):
302
raise errors.InvalidHttpResponse(path, response.text)
303
# The response should be valid JSON, but let's ignore it
304
project = json.loads(response.data)
305
# Spin and wait until import_status for new project
307
deadline = time.time() + timeout
308
while project['import_status'] not in ('finished', 'none'):
309
mutter('import status is %s', project['import_status'])
310
if time.time() > deadline:
311
raise Exception('timeout waiting for project to become available')
313
project = self._get_project(project['path_with_namespace'])
316
def _get_logged_in_username(self):
317
return self._current_user['username']
319
def _list_paged(self, path, parameters=None, per_page=None):
320
if parameters is None:
323
parameters = dict(parameters.items())
325
parameters['per_page'] = str(per_page)
328
parameters['page'] = page
329
response = self._api_request(
331
';'.join(['%s=%s' % item for item in parameters.items()]))
332
if response.status == 403:
333
raise errors.PermissionDenied(response.text)
334
if response.status != 200:
335
raise errors.InvalidHttpResponse(path, response.text)
336
page = response.getheader("X-Next-Page")
337
for entry in json.loads(response.data):
340
def _list_merge_requests(self, owner=None, project=None, state=None):
341
if project is not None:
342
path = 'projects/%s/merge_requests' % urlutils.quote(str(project), '')
344
path = 'merge_requests'
347
parameters['state'] = state
349
parameters['owner_id'] = urlutils.quote(owner, '')
350
return self._list_paged(path, parameters, per_page=DEFAULT_PAGE_SIZE)
352
def _update_merge_request(self, project_id, iid, mr):
353
path = 'projects/%s/merge_requests/%s' % (
354
urlutils.quote(str(project_id), ''), iid)
355
response = self._api_request('PUT', path, fields=mr)
356
if response.status == 200:
357
return json.loads(response.data)
358
raise errors.InvalidHttpResponse(path, response.text)
360
def _create_mergerequest(
361
self, title, source_project_id, target_project_id,
362
source_branch_name, target_branch_name, description,
364
path = 'projects/%s/merge_requests' % source_project_id
367
'source_branch': source_branch_name,
368
'target_branch': target_branch_name,
369
'target_project_id': target_project_id,
370
'description': description,
373
fields['labels'] = labels
374
response = self._api_request('POST', path, fields=fields)
375
if response.status == 403:
376
raise errors.PermissionDenied(response.text)
377
if response.status == 409:
378
raise MergeProposalExists(self.source_branch.user_url)
379
if response.status != 201:
380
raise errors.InvalidHttpResponse(path, response.text)
381
return json.loads(response.data)
383
def get_push_url(self, branch):
384
(host, project_name, branch_name) = parse_gitlab_branch_url(branch)
385
project = self._get_project(project_name)
386
return gitlab_url_to_bzr_url(
387
project['ssh_url_to_repo'], branch_name)
389
def publish_derived(self, local_branch, base_branch, name, project=None,
390
owner=None, revision_id=None, overwrite=False,
392
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
394
owner = self._get_logged_in_username()
396
project = self._get_project(base_project)['path']
398
target_project = self._get_project('%s/%s' % (owner, project))
399
except NoSuchProject:
400
target_project = self._fork_project(base_project)
401
remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
402
remote_dir = controldir.ControlDir.open(remote_repo_url)
404
push_result = remote_dir.push_branch(
405
local_branch, revision_id=revision_id, overwrite=overwrite,
407
except errors.NoRoundtrippingSupport:
410
push_result = remote_dir.push_branch(
411
local_branch, revision_id=revision_id, overwrite=overwrite,
412
name=name, lossy=True)
413
public_url = gitlab_url_to_bzr_url(
414
target_project['http_url_to_repo'], name)
415
return push_result.target_branch, public_url
417
def get_derived_branch(self, base_branch, name, project=None, owner=None):
418
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
420
owner = self._get_logged_in_username()
422
project = self._get_project(base_project)['path']
424
target_project = self._get_project('%s/%s' % (owner, project))
425
except NoSuchProject:
426
raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
427
return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
428
target_project['ssh_url_to_repo'], name))
430
def get_proposer(self, source_branch, target_branch):
431
return GitlabMergeProposalBuilder(self, source_branch, target_branch)
433
def iter_proposals(self, source_branch, target_branch, status):
434
(source_host, source_project_name, source_branch_name) = (
435
parse_gitlab_branch_url(source_branch))
436
(target_host, target_project_name, target_branch_name) = (
437
parse_gitlab_branch_url(target_branch))
438
if source_host != target_host:
439
raise DifferentGitLabInstances(source_host, target_host)
440
source_project = self._get_project(source_project_name)
441
target_project = self._get_project(target_project_name)
442
state = mp_status_to_status(status)
443
for mr in self._list_merge_requests(
444
project=target_project['id'], state=state):
445
if (mr['source_project_id'] != source_project['id'] or
446
mr['source_branch'] != source_branch_name or
447
mr['target_project_id'] != target_project['id'] or
448
mr['target_branch'] != target_branch_name):
450
yield GitLabMergeProposal(self, mr)
452
def hosts(self, branch):
454
(host, project, branch_name) = parse_gitlab_branch_url(branch)
457
return (self.base_url == ('https://%s' % host))
460
response = self._api_request('GET', 'user')
461
if response.status == 200:
462
self._current_user = json.loads(response.data)
465
if json.loads(response.data) == {"message": "401 Unauthorized"}:
466
raise GitLabLoginMissing()
468
raise GitlabLoginError(response.text)
469
raise UnsupportedHoster(url)
472
def probe_from_url(cls, url, possible_transports=None):
474
(host, project) = parse_gitlab_url(url)
476
raise UnsupportedHoster(url)
477
transport = get_transport(
478
'https://%s' % host, possible_transports=possible_transports)
479
credentials = get_credentials_by_url(transport.base)
480
if credentials is not None:
481
return cls(transport, credentials.get('private_token'))
482
raise UnsupportedHoster(url)
485
def iter_instances(cls):
486
for name, credentials in iter_tokens():
487
if 'url' not in credentials:
490
get_transport(credentials['url']),
491
private_token=credentials.get('private_token'))
493
def iter_my_proposals(self, status='open'):
494
state = mp_status_to_status(status)
495
for mp in self._list_merge_requests(
496
owner=self._get_logged_in_username(), state=state):
497
yield GitLabMergeProposal(self, mp)
499
def get_proposal_by_url(self, url):
501
(host, project, merge_id) = parse_gitlab_merge_request_url(url)
503
raise UnsupportedHoster(url)
504
except NotMergeRequestUrl as e:
505
if self.base_url == ('https://%s' % e.host):
508
raise UnsupportedHoster(url)
509
if self.base_url != ('https://%s' % host):
510
raise UnsupportedHoster(url)
511
project = self._get_project(project)
512
mr = project.mergerequests.get(merge_id)
513
return GitLabMergeProposal(mr)
516
class GitlabMergeProposalBuilder(MergeProposalBuilder):
518
def __init__(self, gl, source_branch, target_branch):
520
self.source_branch = source_branch
521
(self.source_host, self.source_project_name, self.source_branch_name) = (
522
parse_gitlab_branch_url(source_branch))
523
self.target_branch = target_branch
524
(self.target_host, self.target_project_name, self.target_branch_name) = (
525
parse_gitlab_branch_url(target_branch))
526
if self.source_host != self.target_host:
527
raise DifferentGitLabInstances(self.source_host, self.target_host)
529
def get_infotext(self):
530
"""Determine the initial comment for the merge proposal."""
532
info.append("Gitlab instance: %s\n" % self.target_host)
533
info.append("Source: %s\n" % self.source_branch.user_url)
534
info.append("Target: %s\n" % self.target_branch.user_url)
537
def get_initial_body(self):
538
"""Get a body for the proposal for the user to modify.
540
:return: a str or None.
544
def create_proposal(self, description, reviewers=None, labels=None,
545
prerequisite_branch=None, commit_message=None):
546
"""Perform the submission."""
547
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
548
if prerequisite_branch is not None:
549
raise PrerequisiteBranchUnsupported(self)
550
# Note that commit_message is ignored, since Gitlab doesn't support it.
551
source_project = self.gl._get_project(self.source_project_name)
552
target_project = self.gl._get_project(self.target_project_name)
553
# TODO(jelmer): Allow setting title explicitly
554
title = description.splitlines()[0]
555
# TODO(jelmer): Allow setting allow_collaboration field
556
# TODO(jelmer): Allow setting milestone field
557
# TODO(jelmer): Allow setting squash field
560
'source_project_id': source_project['id'],
561
'target_project_id': target_project['id'],
562
'source_branch_name': self.source_branch_name,
563
'target_branch_name': self.target_branch_name,
564
'description': description}
566
kwargs['labels'] = ','.join(labels)
568
kwargs['assignee_ids'] = []
569
for reviewer in reviewers:
571
user = self.gl._get_user_by_email(reviewer)
573
user = self.gl._get_user(reviewer)
574
kwargs['assignee_ids'].append(user['id'])
575
merge_request = self.gl._create_mergerequest(**kwargs)
576
return GitLabMergeProposal(self.gl, merge_request)
579
def register_gitlab_instance(shortname, url):
580
"""Register a gitlab instance.
582
:param shortname: Short name (e.g. "gitlab")
583
:param url: URL to the gitlab instance
585
from breezy.bugtracker import (
587
ProjectIntegerBugTracker,
589
tracker_registry.register(
590
shortname, ProjectIntegerBugTracker(
591
shortname, url + '/{project}/issues/{id}'))