/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/plugins/propose/gitlabs.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-03 23:48:08 UTC
  • mfrom: (7316 work)
  • mto: This revision was merged to the branch mainline in revision 7328.
  • Revision ID: jelmer@jelmer.uk-20190603234808-15yk5c7054tj8e2b
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2018 Breezy Developers
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Support for GitLab."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
import os
 
22
 
 
23
from ... import (
 
24
    branch as _mod_branch,
 
25
    controldir,
 
26
    errors,
 
27
    urlutils,
 
28
    )
 
29
from ...git.urls import git_url_to_bzr_url
 
30
from ...sixish import PY3
 
31
from ...transport import get_transport
 
32
 
 
33
from .propose import (
 
34
    Hoster,
 
35
    MergeProposal,
 
36
    MergeProposalBuilder,
 
37
    MergeProposalExists,
 
38
    NoSuchProject,
 
39
    PrerequisiteBranchUnsupported,
 
40
    UnsupportedHoster,
 
41
    )
 
42
 
 
43
 
 
44
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
 
45
 
 
46
 
 
47
def mp_status_to_status(status):
 
48
    return {
 
49
        'all': 'all',
 
50
        'open': 'opened',
 
51
        'merged': 'merged',
 
52
        'closed': 'closed'}[status]
 
53
 
 
54
 
 
55
class NotGitLabUrl(errors.BzrError):
 
56
 
 
57
    _fmt = "Not a GitLab URL: %(url)s"
 
58
 
 
59
    def __init__(self, url):
 
60
        errors.BzrError.__init__(self)
 
61
        self.url = url
 
62
 
 
63
 
 
64
class DifferentGitLabInstances(errors.BzrError):
 
65
 
 
66
    _fmt = ("Can't create merge proposals across GitLab instances: "
 
67
            "%(source_host)s and %(target_host)s")
 
68
 
 
69
    def __init__(self, source_host, target_host):
 
70
        self.source_host = source_host
 
71
        self.target_host = target_host
 
72
 
 
73
 
 
74
class GitLabLoginMissing(errors.BzrError):
 
75
 
 
76
    _fmt = ("Please log into GitLab")
 
77
 
 
78
 
 
79
class GitlabLoginError(errors.BzrError):
 
80
 
 
81
    _fmt = ("Error logging in: %(error)s")
 
82
 
 
83
    def __init__(self, error):
 
84
        self.error = error
 
85
 
 
86
 
 
87
def default_config_path():
 
88
    from breezy.config import config_dir
 
89
    import os
 
90
    return os.path.join(config_dir(), 'gitlab.conf')
 
91
 
 
92
 
 
93
def store_gitlab_token(name, url, private_token):
 
94
    """Store a GitLab token in a configuration file."""
 
95
    import configparser
 
96
    config = configparser.ConfigParser()
 
97
    path = default_config_path()
 
98
    config.read([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:
 
103
        config.write(f)
 
104
 
 
105
 
 
106
def iter_tokens():
 
107
    import configparser
 
108
    config = configparser.ConfigParser()
 
109
    config.read(
 
110
        [os.path.expanduser(p) for p in _DEFAULT_FILES] +
 
111
        [default_config_path()])
 
112
    for name, section in config.items():
 
113
        yield name, section
 
114
 
 
115
 
 
116
def parse_gitlab_url(url):
 
117
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
118
        url)
 
119
    if scheme not in ('git+ssh', 'https', 'http'):
 
120
        raise NotGitLabUrl(url)
 
121
    if not host:
 
122
        raise NotGitLabUrl(url)
 
123
    path = path.strip('/')
 
124
    if path.endswith('.git'):
 
125
        path = path[:-4]
 
126
    return host, path
 
127
 
 
128
 
 
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
 
133
 
 
134
 
 
135
class GitLabMergeProposal(MergeProposal):
 
136
 
 
137
    def __init__(self, gl, mr):
 
138
        self.gl = gl
 
139
        self._mr = mr
 
140
 
 
141
    @property
 
142
    def url(self):
 
143
        return self._mr['web_url']
 
144
 
 
145
    def get_description(self):
 
146
        return self._mr['description']
 
147
 
 
148
    def set_description(self, description):
 
149
        self._mr['description'] = description
 
150
        self.gl._update_merge_requests(self._mr)
 
151
 
 
152
    def get_commit_message(self):
 
153
        return None
 
154
 
 
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)
 
158
 
 
159
    def get_source_branch_url(self):
 
160
        return self._branch_url_from_project(
 
161
            self._mr['source_project_id'], self._mr['source_branch'])
 
162
 
 
163
    def get_target_branch_url(self):
 
164
        return self._branch_url_from_project(
 
165
            self._mr['target_project_id'], self._mr['target_branch'])
 
166
 
 
167
    def is_merged(self):
 
168
        return (self._mr['state'] == 'merged')
 
169
 
 
170
    def close(self):
 
171
        self._mr['state_event'] = 'close'
 
172
        self.gl._update_merge_requests(self._mr)
 
173
 
 
174
 
 
175
def gitlab_url_to_bzr_url(url, name):
 
176
    if not PY3:
 
177
        name = name.encode('utf-8')
 
178
    return urlutils.join_segment_parameters(
 
179
        git_url_to_bzr_url(url), {"branch": name})
 
180
 
 
181
 
 
182
class GitLab(Hoster):
 
183
    """GitLab hoster implementation."""
 
184
 
 
185
    supports_merge_proposal_labels = True
 
186
    supports_merge_proposal_commit_message = False
 
187
 
 
188
    def __repr__(self):
 
189
        return "<GitLab(%r)>" % self.base_url
 
190
 
 
191
    @property
 
192
    def base_url(self):
 
193
        return self.transport.base
 
194
 
 
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)
 
199
 
 
200
    def __init__(self, transport, private_token):
 
201
        self.transport = transport
 
202
        self.headers = {"Private-Token": private_token}
 
203
        self.check()
 
204
 
 
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:
 
211
            return response.json
 
212
        raise InvalidHttpResponse(path, response.text)
 
213
 
 
214
    def _fork_project(self, project_name):
 
215
        path = 'projects/:%s/fork' % urlutils.quote(str(project_name), '')
 
216
        response = self._api_request('POST', path)
 
217
        if response != 200:
 
218
            raise InvalidHttpResponse(path, response.text)
 
219
        return response.json
 
220
 
 
221
    def _get_logged_in_username(self):
 
222
        return self._current_user['username']
 
223
 
 
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), '')
 
227
        else:
 
228
            path = 'merge_requests'
 
229
        parameters = {}
 
230
        if state:
 
231
            parameters['state'] = state
 
232
        if owner:
 
233
            parameters['owner_id'] = urlutils.quote(owner, '')
 
234
        response = self._api_request(
 
235
            'GET', path + '?' +
 
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:
 
240
            return response.json
 
241
        raise InvalidHttpResponse(path, response.text)
 
242
 
 
243
    def _create_mergerequest(
 
244
            self, title, source_project_id, target_project_id,
 
245
            source_branch_name, target_branch_name, description,
 
246
            labels=None):
 
247
        path = 'projects/:%s/merge_requests' % source_project_id
 
248
        response = self._api_request(
 
249
            'POST', path, fields={
 
250
                'title': title,
 
251
                'source_branch': source_branch_name,
 
252
                'target_branch': target_branch_name,
 
253
                'target_project_id': target_project_id,
 
254
                'description': description,
 
255
                'labels': labels})
 
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)
 
262
        return response.json
 
263
 
 
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)
 
269
 
 
270
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
271
                        owner=None, revision_id=None, overwrite=False,
 
272
                        allow_lossy=True):
 
273
        (host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
 
274
        if owner is None:
 
275
            owner = self._get_logged_in_username()
 
276
        if project is None:
 
277
            project = self._get_project(base_project)['path']
 
278
        try:
 
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
 
283
            # is complete.
 
284
        remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
 
285
        remote_dir = controldir.ControlDir.open(remote_repo_url)
 
286
        try:
 
287
            push_result = remote_dir.push_branch(
 
288
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
289
                name=name)
 
290
        except errors.NoRoundtrippingSupport:
 
291
            if not allow_lossy:
 
292
                raise
 
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
 
299
 
 
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)
 
302
        if owner is None:
 
303
            owner = self._get_logged_in_username()
 
304
        if project is None:
 
305
            project = self._get_project(base_project)['path']
 
306
        try:
 
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))
 
312
 
 
313
    def get_proposer(self, source_branch, target_branch):
 
314
        return GitlabMergeProposalBuilder(self, source_branch, target_branch)
 
315
 
 
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):
 
332
                continue
 
333
            yield GitLabMergeProposal(self, mr)
 
334
 
 
335
    def hosts(self, branch):
 
336
        try:
 
337
            (host, project, branch_name) = parse_gitlab_branch_url(branch)
 
338
        except NotGitLabUrl:
 
339
            return False
 
340
        return (self.base_url == ('https://%s' % host))
 
341
 
 
342
    def check(self):
 
343
        response = self._api_request('GET', 'user')
 
344
        if response.status == 200:
 
345
            self._current_user = response.json
 
346
            return
 
347
        if response == 401:
 
348
            if response.json == {"message": "401 Unauthorized"}:
 
349
                raise GitLabLoginMissing()
 
350
            else:
 
351
                raise GitlabLoginError(response.text)
 
352
        raise UnsupportedHoster(url)
 
353
 
 
354
    @classmethod
 
355
    def probe_from_url(cls, url, possible_transports=None):
 
356
        try:
 
357
            (host, project) = parse_gitlab_url(url)
 
358
        except NotGitLabUrl:
 
359
            raise UnsupportedHoster(url)
 
360
        transport = get_transport(
 
361
            'https://%s' % host, possible_transports=possible_transports)
 
362
        return cls(transport)
 
363
 
 
364
    @classmethod
 
365
    def iter_instances(cls):
 
366
        for name, credentials in iter_tokens():
 
367
            if 'url' not in credentials:
 
368
                continue
 
369
            yield cls(
 
370
                get_transport(credentials['url']),
 
371
                private_token=credentials.get('private_token'))
 
372
 
 
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)
 
378
 
 
379
 
 
380
class GitlabMergeProposalBuilder(MergeProposalBuilder):
 
381
 
 
382
    def __init__(self, l, source_branch, target_branch):
 
383
        self.gl = gl
 
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)
 
392
 
 
393
    def get_infotext(self):
 
394
        """Determine the initial comment for the merge proposal."""
 
395
        info = []
 
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)
 
399
        return ''.join(info)
 
400
 
 
401
    def get_initial_body(self):
 
402
        """Get a body for the proposal for the user to modify.
 
403
 
 
404
        :return: a str or None.
 
405
        """
 
406
        return None
 
407
 
 
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
 
423
        kwargs = {
 
424
            'title': title,
 
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}
 
430
        if labels:
 
431
            kwargs['labels'] = ','.join(labels)
 
432
        merge_request = self.gl._create_mergerequest(**kwargs)
 
433
        return GitLabMergeProposal(self.gl, merge_request)
 
434
 
 
435
 
 
436
def register_gitlab_instance(shortname, url):
 
437
    """Register a gitlab instance.
 
438
 
 
439
    :param shortname: Short name (e.g. "gitlab")
 
440
    :param url: URL to the gitlab instance
 
441
    """
 
442
    from breezy.bugtracker import (
 
443
        tracker_registry,
 
444
        ProjectIntegerBugTracker,
 
445
        )
 
446
    tracker_registry.register(
 
447
        shortname, ProjectIntegerBugTracker(
 
448
            shortname, url + '/{project}/issues/{id}'))