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
25
branch as _mod_branch,
30
from ...git.urls import git_url_to_bzr_url
31
from ...sixish import PY3
32
from ...transport import get_transport
34
from .propose import (
40
PrerequisiteBranchUnsupported,
45
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
48
def mp_status_to_status(status):
53
'closed': 'closed'}[status]
56
class NotGitLabUrl(errors.BzrError):
58
_fmt = "Not a GitLab URL: %(url)s"
60
def __init__(self, url):
61
errors.BzrError.__init__(self)
65
class NotMergeRequestUrl(errors.BzrError):
67
_fmt = "Not a merge proposal URL: %(url)s"
69
def __init__(self, host, url):
70
errors.BzrError.__init__(self)
75
class DifferentGitLabInstances(errors.BzrError):
77
_fmt = ("Can't create merge proposals across GitLab instances: "
78
"%(source_host)s and %(target_host)s")
80
def __init__(self, source_host, target_host):
81
self.source_host = source_host
82
self.target_host = target_host
85
class GitLabLoginMissing(errors.BzrError):
87
_fmt = ("Please log into GitLab")
90
class GitlabLoginError(errors.BzrError):
92
_fmt = ("Error logging in: %(error)s")
94
def __init__(self, error):
98
def default_config_path():
99
from breezy.config import config_dir
101
return os.path.join(config_dir(), 'gitlab.conf')
104
def store_gitlab_token(name, url, private_token):
105
"""Store a GitLab token in a configuration file."""
107
config = configparser.ConfigParser()
108
path = default_config_path()
110
config.add_section(name)
111
config[name]['url'] = url
112
config[name]['private_token'] = private_token
113
with open(path, 'w') as f:
119
config = configparser.ConfigParser()
121
[os.path.expanduser(p) for p in _DEFAULT_FILES] +
122
[default_config_path()])
123
for name, section in config.items():
127
def parse_gitlab_url(url):
128
(scheme, user, password, host, port, path) = urlutils.parse_url(
130
if scheme not in ('git+ssh', 'https', 'http'):
131
raise NotGitLabUrl(url)
133
raise NotGitLabUrl(url)
134
path = path.strip('/')
135
if path.endswith('.git'):
140
def parse_gitlab_branch_url(branch):
141
url = urlutils.split_segment_parameters(branch.user_url)[0]
142
host, path = parse_gitlab_url(url)
143
return host, path, branch.name
146
def parse_gitlab_merge_request_url(url):
147
(scheme, user, password, host, port, path) = urlutils.parse_url(
149
if scheme not in ('git+ssh', 'https', 'http'):
150
raise NotGitLabUrl(url)
152
raise NotGitLabUrl(url)
153
path = path.strip('/')
154
parts = path.split('/')
155
if parts[-2] != 'merge_requests':
156
raise NotMergeRequestUrl(host, url)
157
return host, '/'.join(parts[:-2]), int(parts[-1])
160
class GitLabMergeProposal(MergeProposal):
162
def __init__(self, gl, mr):
168
return self._mr['web_url']
170
def get_description(self):
171
return self._mr['description']
173
def set_description(self, description):
174
self._mr['description'] = description
175
self.gl._update_merge_requests(self._mr)
177
def get_commit_message(self):
180
def _branch_url_from_project(self, project_id, branch_name):
181
project = self.gl._get_project(project_id)
182
return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
184
def get_source_branch_url(self):
185
return self._branch_url_from_project(
186
self._mr['source_project_id'], self._mr['source_branch'])
188
def get_target_branch_url(self):
189
return self._branch_url_from_project(
190
self._mr['target_project_id'], self._mr['target_branch'])
193
return (self._mr['state'] == 'merged')
196
self._mr['state_event'] = 'close'
197
self.gl._update_merge_requests(self._mr)
199
def merge(self, commit_message=None):
200
# https://docs.gitlab.com/ee/api/merge_requests.html#accept-mr
201
self._mr.merge(merge_commit_message=commit_message)
204
def gitlab_url_to_bzr_url(url, name):
206
name = name.encode('utf-8')
207
return urlutils.join_segment_parameters(
208
git_url_to_bzr_url(url), {"branch": name})
211
class GitLab(Hoster):
212
"""GitLab hoster implementation."""
214
supports_merge_proposal_labels = True
215
supports_merge_proposal_commit_message = False
218
return "<GitLab(%r)>" % self.base_url
222
return self.transport.base
224
def _api_request(self, method, path):
225
return self.transport.request(
226
method, urlutils.join(self.base_url, 'api', 'v4', path),
227
headers=self.headers)
229
def __init__(self, transport, private_token):
230
self.transport = transport
231
self.headers = {"Private-Token": private_token}
234
def _get_project(self, project_name):
235
path = 'projects/:%s' % urlutils.quote(str(project_name), '')
236
response = self._api_request('GET', path)
237
if response.status == 404:
238
raise NoSuchProject(project_name)
239
if response.status == 200:
240
return json.loads(response.data)
241
raise InvalidHttpResponse(path, response.text)
243
def _fork_project(self, project_name):
244
path = 'projects/:%s/fork' % urlutils.quote(str(project_name), '')
245
response = self._api_request('POST', path)
247
raise InvalidHttpResponse(path, response.text)
248
return json.loads(response.data)
250
def _get_logged_in_username(self):
251
return self._current_user['username']
253
def _list_merge_requests(self, owner=None, project=None, state=None):
254
if project is not None:
255
path = 'projects/:%s/merge_requests' % urlutils.quote(str(project_name), '')
257
path = 'merge_requests'
260
parameters['state'] = state
262
parameters['owner_id'] = urlutils.quote(owner, '')
263
response = self._api_request(
265
';'.join(['%s=%s' % item for item in parameters.items()]))
266
if response.status == 403:
267
raise errors.PermissionDenied(response.text)
268
if response.status == 200:
269
return json.loads(response.data)
270
raise InvalidHttpResponse(path, response.text)
272
def _create_mergerequest(
273
self, title, source_project_id, target_project_id,
274
source_branch_name, target_branch_name, description,
276
path = 'projects/:%s/merge_requests' % source_project_id
277
response = self._api_request(
278
'POST', path, fields={
280
'source_branch': source_branch_name,
281
'target_branch': target_branch_name,
282
'target_project_id': target_project_id,
283
'description': description,
285
if response.status == 403:
286
raise errors.PermissionDenied(response.text)
287
if response.status == 409:
288
raise MergeProposalExists(self.source_branch.user_url)
289
if response.status == 200:
290
raise InvalidHttpResponse(path, response.text)
291
return json.loads(response.data)
293
def get_push_url(self, branch):
294
(host, project_name, branch_name) = parse_gitlab_branch_url(branch)
295
project = self._get_project(project_name)
296
return gitlab_url_to_bzr_url(
297
project['ssh_url_to_repo'], branch_name)
299
def publish_derived(self, local_branch, base_branch, name, project=None,
300
owner=None, revision_id=None, overwrite=False,
302
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
304
owner = self._get_logged_in_username()
306
project = self._get_project(base_project)['path']
308
target_project = self._get_project('%s/%s' % (owner, project))
309
except NoSuchProject:
310
target_project = self._fork_project(base_project)
311
# TODO(jelmer): Spin and wait until import_status for new project
313
remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
314
remote_dir = controldir.ControlDir.open(remote_repo_url)
316
push_result = remote_dir.push_branch(
317
local_branch, revision_id=revision_id, overwrite=overwrite,
319
except errors.NoRoundtrippingSupport:
322
push_result = remote_dir.push_branch(
323
local_branch, revision_id=revision_id, overwrite=overwrite,
324
name=name, lossy=True)
325
public_url = gitlab_url_to_bzr_url(
326
target_project['http_url_to_repo'], name)
327
return push_result.target_branch, public_url
329
def get_derived_branch(self, base_branch, name, project=None, owner=None):
330
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
332
owner = self._get_logged_in_username()
334
project = self._get_project(base_project)['path']
336
target_project = self._get_project('%s/%s' % (owner, project))
337
except NoSuchProject:
338
raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
339
return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
340
target_project['ssh_url_to_repo'], name))
342
def get_proposer(self, source_branch, target_branch):
343
return GitlabMergeProposalBuilder(self, source_branch, target_branch)
345
def iter_proposals(self, source_branch, target_branch, status):
346
(source_host, source_project_name, source_branch_name) = (
347
parse_gitlab_branch_url(source_branch))
348
(target_host, target_project_name, target_branch_name) = (
349
parse_gitlab_branch_url(target_branch))
350
if source_host != target_host:
351
raise DifferentGitLabInstances(source_host, target_host)
352
source_project = self._get_project(source_project_name)
353
target_project = self._get_project(target_project_name)
354
state = mp_status_to_status(status)
355
for mr in self.gl._list_merge_requests(
356
project=target_project['id'], state=state):
357
if (mr['source_project_id'] != source_project['id'] or
358
mr['source_branch'] != source_branch_name or
359
mr['target_project_id'] != target_project['id'] or
360
mr['target_branch'] != target_branch_name):
362
yield GitLabMergeProposal(self, mr)
364
def hosts(self, branch):
366
(host, project, branch_name) = parse_gitlab_branch_url(branch)
369
return (self.base_url == ('https://%s' % host))
372
response = self._api_request('GET', 'user')
373
if response.status == 200:
374
self._current_user = json.loads(response.data)
377
if json.loads(response.data) == {"message": "401 Unauthorized"}:
378
raise GitLabLoginMissing()
380
raise GitlabLoginError(response.text)
381
raise UnsupportedHoster(url)
384
def probe_from_url(cls, url, possible_transports=None):
386
(host, project) = parse_gitlab_url(url)
388
raise UnsupportedHoster(url)
389
transport = get_transport(
390
'https://%s' % host, possible_transports=possible_transports)
391
return cls(transport)
394
def iter_instances(cls):
395
for name, credentials in iter_tokens():
396
if 'url' not in credentials:
399
get_transport(credentials['url']),
400
private_token=credentials.get('private_token'))
402
def iter_my_proposals(self, status='open'):
403
state = mp_status_to_status(status)
404
for mp in self._list_merge_requests(
405
owner=self._get_logged_in_username(), state=state):
406
yield GitLabMergeProposal(self, mp)
408
def get_proposal_by_url(self, url):
410
(host, project, merge_id) = parse_gitlab_merge_request_url(url)
412
raise UnsupportedHoster(url)
413
except NotMergeRequestUrl as e:
414
if self.gl.url == ('https://%s' % e.host):
417
raise UnsupportedHoster(url)
418
if self.gl.url != ('https://%s' % host):
419
raise UnsupportedHoster(url)
420
project = self.gl.projects.get(project)
421
mr = project.mergerequests.get(merge_id)
422
return GitLabMergeProposal(mr)
425
class GitlabMergeProposalBuilder(MergeProposalBuilder):
427
def __init__(self, l, source_branch, target_branch):
429
self.source_branch = source_branch
430
(self.source_host, self.source_project_name, self.source_branch_name) = (
431
parse_gitlab_branch_url(source_branch))
432
self.target_branch = target_branch
433
(self.target_host, self.target_project_name, self.target_branch_name) = (
434
parse_gitlab_branch_url(target_branch))
435
if self.source_host != self.target_host:
436
raise DifferentGitLabInstances(self.source_host, self.target_host)
438
def get_infotext(self):
439
"""Determine the initial comment for the merge proposal."""
441
info.append("Gitlab instance: %s\n" % self.target_host)
442
info.append("Source: %s\n" % self.source_branch.user_url)
443
info.append("Target: %s\n" % self.target_branch.user_url)
446
def get_initial_body(self):
447
"""Get a body for the proposal for the user to modify.
449
:return: a str or None.
453
def create_proposal(self, description, reviewers=None, labels=None,
454
prerequisite_branch=None, commit_message=None):
455
"""Perform the submission."""
456
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
457
if prerequisite_branch is not None:
458
raise PrerequisiteBranchUnsupported(self)
459
# Note that commit_message is ignored, since Gitlab doesn't support it.
460
# TODO(jelmer): Support reviewers
461
source_project = self.gl._get_project(self.source_project_name)
462
target_project = self.gl._get_project(self.target_project_name)
463
# TODO(jelmer): Allow setting title explicitly
464
title = description.splitlines()[0]
465
# TODO(jelmer): Allow setting allow_collaboration field
466
# TODO(jelmer): Allow setting milestone field
467
# TODO(jelmer): Allow setting squash field
470
'source_project_id': source_project['id'],
471
'target_project_id': target_project['id'],
472
'source_branch': self.source_branch_name,
473
'target_branch': self.target_branch_name,
474
'description': description}
476
kwargs['labels'] = ','.join(labels)
477
merge_request = self.gl._create_mergerequest(**kwargs)
478
return GitLabMergeProposal(self.gl, merge_request)
481
def register_gitlab_instance(shortname, url):
482
"""Register a gitlab instance.
484
:param shortname: Short name (e.g. "gitlab")
485
:param url: URL to the gitlab instance
487
from breezy.bugtracker import (
489
ProjectIntegerBugTracker,
491
tracker_registry.register(
492
shortname, ProjectIntegerBugTracker(
493
shortname, url + '/{project}/issues/{id}'))