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
24
branch as _mod_branch,
29
from ...git.urls import git_url_to_bzr_url
30
from ...sixish import PY3
31
from ...transport import get_transport
33
from .propose import (
39
PrerequisiteBranchUnsupported,
44
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
47
def mp_status_to_status(status):
52
'closed': 'closed'}[status]
55
class NotGitLabUrl(errors.BzrError):
57
_fmt = "Not a GitLab URL: %(url)s"
59
def __init__(self, url):
60
errors.BzrError.__init__(self)
64
class DifferentGitLabInstances(errors.BzrError):
66
_fmt = ("Can't create merge proposals across GitLab instances: "
67
"%(source_host)s and %(target_host)s")
69
def __init__(self, source_host, target_host):
70
self.source_host = source_host
71
self.target_host = target_host
74
class GitLabLoginMissing(errors.BzrError):
76
_fmt = ("Please log into GitLab")
79
class GitlabLoginError(errors.BzrError):
81
_fmt = ("Error logging in: %(error)s")
83
def __init__(self, error):
87
def default_config_path():
88
from breezy.config import config_dir
90
return os.path.join(config_dir(), 'gitlab.conf')
93
def store_gitlab_token(name, url, private_token):
94
"""Store a GitLab token in a configuration file."""
96
config = configparser.ConfigParser()
97
path = default_config_path()
99
config.add_section(name)
100
config[name]['url'] = url
101
config[name]['private_token'] = private_token
102
with open(path, 'w') as f:
108
config = configparser.ConfigParser()
110
[os.path.expanduser(p) for p in _DEFAULT_FILES] +
111
[default_config_path()])
112
for name, section in config.items():
116
def parse_gitlab_url(url):
117
(scheme, user, password, host, port, path) = urlutils.parse_url(
119
if scheme not in ('git+ssh', 'https', 'http'):
120
raise NotGitLabUrl(url)
122
raise NotGitLabUrl(url)
123
path = path.strip('/')
124
if path.endswith('.git'):
129
def parse_gitlab_branch_url(branch):
130
url = urlutils.split_segment_parameters(branch.user_url)[0]
131
host, path = parse_gitlab_url(url)
132
return host, path, branch.name
135
class GitLabMergeProposal(MergeProposal):
137
def __init__(self, gl, mr):
143
return self._mr['web_url']
145
def get_description(self):
146
return self._mr['description']
148
def set_description(self, description):
149
self._mr['description'] = description
150
self.gl._update_merge_requests(self._mr)
152
def get_commit_message(self):
155
def _branch_url_from_project(self, project_id, branch_name):
156
project = self.gl._get_project(project_id)
157
return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
159
def get_source_branch_url(self):
160
return self._branch_url_from_project(
161
self._mr['source_project_id'], self._mr['source_branch'])
163
def get_target_branch_url(self):
164
return self._branch_url_from_project(
165
self._mr['target_project_id'], self._mr['target_branch'])
168
return (self._mr['state'] == 'merged')
171
self._mr['state_event'] = 'close'
172
self.gl._update_merge_requests(self._mr)
175
def gitlab_url_to_bzr_url(url, name):
177
name = name.encode('utf-8')
178
return urlutils.join_segment_parameters(
179
git_url_to_bzr_url(url), {"branch": name})
182
class GitLab(Hoster):
183
"""GitLab hoster implementation."""
185
supports_merge_proposal_labels = True
186
supports_merge_proposal_commit_message = False
189
return "<GitLab(%r)>" % self.base_url
193
return self.transport.base
195
def _api_request(self, method, path):
196
return self.transport.request(
197
method, urlutils.join(self.base_url, 'api', 'v4', path),
198
headers=self.headers)
200
def __init__(self, transport, private_token):
201
self.transport = transport
202
self.headers = {"Private-Token": private_token}
205
def _get_project(self, project_name):
206
path = 'projects/:%s' % urlutils.quote(str(project_name), '')
207
response = self._api_request('GET', path)
208
if response.status == 404:
209
raise NoSuchProject(project_name)
210
if response.status == 200:
212
raise InvalidHttpResponse(path, response.text)
214
def _fork_project(self, project_name):
215
path = 'projects/:%s/fork' % urlutils.quote(str(project_name), '')
216
response = self._api_request('POST', path)
218
raise InvalidHttpResponse(path, response.text)
221
def _get_logged_in_username(self):
222
return self._current_user['username']
224
def _list_mergerequests(self, owner=None, project=None, state=None):
225
if project is not None:
226
path = 'projects/:%s/merge_requests' % urlutils.quote(str(project_name), '')
228
path = 'merge_requests'
231
parameters['state'] = state
233
parameters['owner_id'] = urlutils.quote(owner, '')
234
response = self._api_request(
236
';'.join(['%s=%s' % item for item in parameters.items()]))
237
if response.status == 403:
238
raise errors.PermissionDenied(response.text)
239
if response.status == 200:
241
raise InvalidHttpResponse(path, response.text)
243
def _create_mergerequest(
244
self, title, source_project_id, target_project_id,
245
source_branch_name, target_branch_name, description,
247
path = 'projects/:%s/merge_requests' % source_project_id
248
response = self._api_request(
249
'POST', path, fields={
251
'source_branch': source_branch_name,
252
'target_branch': target_branch_name,
253
'target_project_id': target_project_id,
254
'description': description,
256
if response.status == 403:
257
raise errors.PermissionDenied(response.text)
258
if response.status == 409:
259
raise MergeProposalExists(self.source_branch.user_url)
260
if response.status == 200:
261
raise InvalidHttpResponse(path, response.text)
264
def get_push_url(self, branch):
265
(host, project_name, branch_name) = parse_gitlab_branch_url(branch)
266
project = self._get_project(project_name)
267
return gitlab_url_to_bzr_url(
268
project['ssh_url_to_repo'], branch_name)
270
def publish_derived(self, local_branch, base_branch, name, project=None,
271
owner=None, revision_id=None, overwrite=False,
273
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
275
owner = self._get_logged_in_username()
277
project = self._get_project(base_project)['path']
279
target_project = self._get_project('%s/%s' % (owner, project))
280
except NoSuchProject:
281
target_project = self._fork_project(base_project)
282
# TODO(jelmer): Spin and wait until import_status for new project
284
remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
285
remote_dir = controldir.ControlDir.open(remote_repo_url)
287
push_result = remote_dir.push_branch(
288
local_branch, revision_id=revision_id, overwrite=overwrite,
290
except errors.NoRoundtrippingSupport:
293
push_result = remote_dir.push_branch(
294
local_branch, revision_id=revision_id, overwrite=overwrite,
295
name=name, lossy=True)
296
public_url = gitlab_url_to_bzr_url(
297
target_project['http_url_to_repo'], name)
298
return push_result.target_branch, public_url
300
def get_derived_branch(self, base_branch, name, project=None, owner=None):
301
(host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
303
owner = self._get_logged_in_username()
305
project = self._get_project(base_project)['path']
307
target_project = self._get_project('%s/%s' % (owner, project))
308
except NoSuchProject:
309
raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
310
return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
311
target_project['ssh_url_to_repo'], name))
313
def get_proposer(self, source_branch, target_branch):
314
return GitlabMergeProposalBuilder(self, source_branch, target_branch)
316
def iter_proposals(self, source_branch, target_branch, status):
317
(source_host, source_project_name, source_branch_name) = (
318
parse_gitlab_branch_url(source_branch))
319
(target_host, target_project_name, target_branch_name) = (
320
parse_gitlab_branch_url(target_branch))
321
if source_host != target_host:
322
raise DifferentGitLabInstances(source_host, target_host)
323
source_project = self._get_project(source_project_name)
324
target_project = self._get_project(target_project_name)
325
state = mp_status_to_status(status)
326
for mr in self.gl._list_mergerequests(
327
project=target_project['id'], state=state):
328
if (mr['source_project_id'] != source_project['id'] or
329
mr['source_branch'] != source_branch_name or
330
mr['target_project_id'] != target_project['id'] or
331
mr['target_branch'] != target_branch_name):
333
yield GitLabMergeProposal(self, mr)
335
def hosts(self, branch):
337
(host, project, branch_name) = parse_gitlab_branch_url(branch)
340
return (self.base_url == ('https://%s' % host))
343
response = self._api_request('GET', 'user')
344
if response.status == 200:
345
self._current_user = response.json
348
if response.json == {"message": "401 Unauthorized"}:
349
raise GitLabLoginMissing()
351
raise GitlabLoginError(response.text)
352
raise UnsupportedHoster(url)
355
def probe_from_url(cls, url, possible_transports=None):
357
(host, project) = parse_gitlab_url(url)
359
raise UnsupportedHoster(url)
360
transport = get_transport(
361
'https://%s' % host, possible_transports=possible_transports)
362
return cls(transport)
365
def iter_instances(cls):
366
for name, credentials in iter_tokens():
367
if 'url' not in credentials:
370
get_transport(credentials['url']),
371
private_token=credentials.get('private_token'))
373
def iter_my_proposals(self, status='open'):
374
state = mp_status_to_status(status)
375
for mp in self._list_mergerequests(
376
owner=self._get_logged_in_username(), state=state):
377
yield GitLabMergeProposal(self, mp)
380
class GitlabMergeProposalBuilder(MergeProposalBuilder):
382
def __init__(self, l, source_branch, target_branch):
384
self.source_branch = source_branch
385
(self.source_host, self.source_project_name, self.source_branch_name) = (
386
parse_gitlab_branch_url(source_branch))
387
self.target_branch = target_branch
388
(self.target_host, self.target_project_name, self.target_branch_name) = (
389
parse_gitlab_branch_url(target_branch))
390
if self.source_host != self.target_host:
391
raise DifferentGitLabInstances(self.source_host, self.target_host)
393
def get_infotext(self):
394
"""Determine the initial comment for the merge proposal."""
396
info.append("Gitlab instance: %s\n" % self.target_host)
397
info.append("Source: %s\n" % self.source_branch.user_url)
398
info.append("Target: %s\n" % self.target_branch.user_url)
401
def get_initial_body(self):
402
"""Get a body for the proposal for the user to modify.
404
:return: a str or None.
408
def create_proposal(self, description, reviewers=None, labels=None,
409
prerequisite_branch=None, commit_message=None):
410
"""Perform the submission."""
411
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
412
if prerequisite_branch is not None:
413
raise PrerequisiteBranchUnsupported(self)
414
# Note that commit_message is ignored, since Gitlab doesn't support it.
415
# TODO(jelmer): Support reviewers
416
source_project = self.gl._get_project(self.source_project_name)
417
target_project = self.gl._get_project(self.target_project_name)
418
# TODO(jelmer): Allow setting title explicitly
419
title = description.splitlines()[0]
420
# TODO(jelmer): Allow setting allow_collaboration field
421
# TODO(jelmer): Allow setting milestone field
422
# TODO(jelmer): Allow setting squash field
425
'source_project_id': source_project['id'],
426
'target_project_id': target_project['id'],
427
'source_branch': self.source_branch_name,
428
'target_branch': self.target_branch_name,
429
'description': description}
431
kwargs['labels'] = ','.join(labels)
432
merge_request = self.gl._create_mergerequest(**kwargs)
433
return GitLabMergeProposal(self.gl, merge_request)
436
def register_gitlab_instance(shortname, url):
437
"""Register a gitlab instance.
439
:param shortname: Short name (e.g. "gitlab")
440
:param url: URL to the gitlab instance
442
from breezy.bugtracker import (
444
ProjectIntegerBugTracker,
446
tracker_registry.register(
447
shortname, ProjectIntegerBugTracker(
448
shortname, url + '/{project}/issues/{id}'))