/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
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
0.434.1 by Jelmer Vernooij
Use absolute_import.
17
"""Support for GitLab."""
18
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
19
from __future__ import absolute_import
20
7296.10.8 by Jelmer Vernooij
Remove json attribute from Response object, consistent with urllib3 API.
21
import json
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
22
import os
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
23
import time
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
24
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
25
from ... import (
7340.1.1 by Martin
Fix use of config_dir in propose plugin
26
    bedding,
0.431.33 by Jelmer Vernooij
Fix URLs from gitlab.
27
    branch as _mod_branch,
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
28
    controldir,
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
29
    errors,
30
    urlutils,
31
    )
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
32
from ...git.urls import git_url_to_bzr_url
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
33
from ...sixish import PY3
7380.1.2 by Jelmer Vernooij
Review comments.
34
from ...trace import mutter
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
35
from ...transport import get_transport
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
36
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
37
from .propose import (
0.432.2 by Jelmer Vernooij
Publish command sort of works.
38
    Hoster,
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
39
    MergeProposal,
0.432.2 by Jelmer Vernooij
Publish command sort of works.
40
    MergeProposalBuilder,
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
41
    MergeProposalExists,
0.431.38 by Jelmer Vernooij
Add NoSuchProject.
42
    NoSuchProject,
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
43
    PrerequisiteBranchUnsupported,
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
44
    UnsupportedHoster,
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
45
    )
46
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
47
48
_DEFAULT_FILES = ['/etc/python-gitlab.cfg', '~/.python-gitlab.cfg']
7408.1.2 by Jelmer Vernooij
Set default page size to 50.
49
DEFAULT_PAGE_SIZE = 50
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
50
51
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
52
def mp_status_to_status(status):
53
    return {
54
        'all': 'all',
55
        'open': 'opened',
56
        'merged': 'merged',
57
        'closed': 'closed'}[status]
58
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
59
0.431.17 by Jelmer Vernooij
Try harder to avoid detecting any URL as a GitLab URL.
60
class NotGitLabUrl(errors.BzrError):
61
62
    _fmt = "Not a GitLab URL: %(url)s"
63
64
    def __init__(self, url):
65
        errors.BzrError.__init__(self)
66
        self.url = url
67
68
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
69
class NotMergeRequestUrl(errors.BzrError):
70
71
    _fmt = "Not a merge proposal URL: %(url)s"
72
73
    def __init__(self, host, url):
74
        errors.BzrError.__init__(self)
75
        self.host = host
76
        self.url = url
77
78
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
79
class DifferentGitLabInstances(errors.BzrError):
80
81
    _fmt = ("Can't create merge proposals across GitLab instances: "
82
            "%(source_host)s and %(target_host)s")
83
84
    def __init__(self, source_host, target_host):
85
        self.source_host = source_host
86
        self.target_host = target_host
87
88
0.432.10 by Jelmer Vernooij
More test fixes.
89
class GitLabLoginMissing(errors.BzrError):
90
91
    _fmt = ("Please log into GitLab")
92
93
7296.10.2 by Jelmer Vernooij
More fixes.
94
class GitlabLoginError(errors.BzrError):
95
96
    _fmt = ("Error logging in: %(error)s")
97
98
    def __init__(self, error):
99
        self.error = error
100
101
0.431.59 by Jelmer Vernooij
Add gitlab-login command.
102
def default_config_path():
7340.1.1 by Martin
Fix use of config_dir in propose plugin
103
    return os.path.join(bedding.config_dir(), 'gitlab.conf')
0.431.59 by Jelmer Vernooij
Add gitlab-login command.
104
105
106
def store_gitlab_token(name, url, private_token):
107
    """Store a GitLab token in a configuration file."""
108
    import configparser
109
    config = configparser.ConfigParser()
110
    path = default_config_path()
111
    config.read([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:
116
        config.write(f)
117
118
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
119
def iter_tokens():
120
    import configparser
121
    config = configparser.ConfigParser()
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
122
    config.read(
123
        [os.path.expanduser(p) for p in _DEFAULT_FILES] +
124
        [default_config_path()])
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
125
    for name, section in config.items():
126
        yield name, section
127
128
7359.1.2 by Jelmer Vernooij
Some fixes for gitlab API.
129
def get_credentials_by_url(url):
130
    for name, credentials in iter_tokens():
131
        if 'url' not in credentials:
132
            continue
133
        if credentials['url'].rstrip('/') == url.rstrip('/'):
134
            return credentials
135
    else:
136
        return None
137
138
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
139
def parse_gitlab_url(url):
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
140
    (scheme, user, password, host, port, path) = urlutils.parse_url(
141
        url)
0.431.17 by Jelmer Vernooij
Try harder to avoid detecting any URL as a GitLab URL.
142
    if scheme not in ('git+ssh', 'https', 'http'):
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
143
        raise NotGitLabUrl(url)
0.431.17 by Jelmer Vernooij
Try harder to avoid detecting any URL as a GitLab URL.
144
    if not host:
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
145
        raise NotGitLabUrl(url)
0.432.10 by Jelmer Vernooij
More test fixes.
146
    path = path.strip('/')
0.432.11 by Jelmer Vernooij
Fix some tests.
147
    if path.endswith('.git'):
148
        path = path[:-4]
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
149
    return host, path
150
151
152
def parse_gitlab_branch_url(branch):
153
    url = urlutils.split_segment_parameters(branch.user_url)[0]
154
    host, path = parse_gitlab_url(url)
0.432.10 by Jelmer Vernooij
More test fixes.
155
    return host, path, branch.name
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
156
157
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
158
def parse_gitlab_merge_request_url(url):
159
    (scheme, user, password, host, port, path) = urlutils.parse_url(
160
        url)
161
    if scheme not in ('git+ssh', 'https', 'http'):
162
        raise NotGitLabUrl(url)
163
    if not host:
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])
170
171
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
172
class GitLabMergeProposal(MergeProposal):
173
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
174
    def __init__(self, gl, mr):
175
        self.gl = gl
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
176
        self._mr = mr
177
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
178
    def _update(self, **kwargs):
179
        self.gl._update_merge_request(self._mr['project_id'], self._mr['iid'], kwargs)
180
7381.5.1 by Jelmer Vernooij
Several more fixes for merge proposals. Add functions for reopening merge proposals.
181
    def __repr__(self):
182
        return "<%s at %r>" % (type(self).__name__, self._mr['web_url'])
183
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
184
    @property
185
    def url(self):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
186
        return self._mr['web_url']
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
187
188
    def get_description(self):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
189
        return self._mr['description']
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
190
191
    def set_description(self, description):
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
192
        self._update(description=description, title=description.splitlines()[0])
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
193
7296.8.2 by Jelmer Vernooij
Add feature flag for commit message.
194
    def get_commit_message(self):
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
195
        return self._mr.get('merge_commit_message')
196
197
    def set_commit_message(self, message):
198
        raise errors.UnsupportedOperation(self.set_commit_message, self)
7296.8.2 by Jelmer Vernooij
Add feature flag for commit message.
199
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
200
    def _branch_url_from_project(self, project_id, branch_name):
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
201
        if project_id is None:
202
            return None
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
203
        project = self.gl._get_project(project_id)
7296.10.3 by Jelmer Vernooij
More fixes.
204
        return gitlab_url_to_bzr_url(project['http_url_to_repo'], branch_name)
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
205
206
    def get_source_branch_url(self):
207
        return self._branch_url_from_project(
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
208
            self._mr['source_project_id'], self._mr['source_branch'])
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
209
210
    def get_target_branch_url(self):
211
        return self._branch_url_from_project(
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
212
            self._mr['target_project_id'], self._mr['target_branch'])
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
213
0.431.46 by Jelmer Vernooij
Add MergeProposal.is_merged.
214
    def is_merged(self):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
215
        return (self._mr['state'] == 'merged')
0.431.46 by Jelmer Vernooij
Add MergeProposal.is_merged.
216
7381.5.1 by Jelmer Vernooij
Several more fixes for merge proposals. Add functions for reopening merge proposals.
217
    def is_closed(self):
218
        return (self._mr['state'] == 'closed')
219
220
    def reopen(self):
221
        return self._update(state_event='open')
222
7260.2.1 by Jelmer Vernooij
Implement .close on merge proposals.
223
    def close(self):
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
224
        self._update(state_event='close')
7260.2.1 by Jelmer Vernooij
Implement .close on merge proposals.
225
7296.9.1 by Jelmer Vernooij
Add 'brz land' subcommand.
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)
229
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
230
    def can_be_merged(self):
231
        if self._mr['merge_status'] == 'cannot_be_merged':
232
            return False
233
        elif self._mr['merge_status'] == 'can_be_merged':
234
            return True
235
        else:
236
            raise ValueError(self._mr['merge_status'])
237
7414.4.1 by Jelmer Vernooij
Add a MergeProposal.get_merged_by method.
238
    def get_merged_by(self):
239
        return self._mr.get('merged_by')
240
0.431.39 by Jelmer Vernooij
Extend the merge proposal abstraction a bit.
241
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
242
def gitlab_url_to_bzr_url(url, name):
243
    if not PY3:
244
        name = name.encode('utf-8')
7408.2.1 by Jelmer Vernooij
Use standard functions for creating Git URLs.
245
    return git_url_to_bzr_url(url, branch=name)
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
246
247
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
248
class GitLab(Hoster):
249
    """GitLab hoster implementation."""
250
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
251
    supports_merge_proposal_labels = True
7296.8.2 by Jelmer Vernooij
Add feature flag for commit message.
252
    supports_merge_proposal_commit_message = False
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
253
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
254
    def __repr__(self):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
255
        return "<GitLab(%r)>" % self.base_url
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
256
7260.1.1 by Jelmer Vernooij
Add .base_url property to Hoster.
257
    @property
258
    def base_url(self):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
259
        return self.transport.base
260
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
261
    def _api_request(self, method, path, fields=None):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
262
        return self.transport.request(
263
            method, urlutils.join(self.base_url, 'api', 'v4', path),
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
264
            headers=self.headers, fields=fields)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
265
266
    def __init__(self, transport, private_token):
267
        self.transport = transport
268
        self.headers = {"Private-Token": private_token}
269
        self.check()
270
7381.5.1 by Jelmer Vernooij
Several more fixes for merge proposals. Add functions for reopening merge proposals.
271
    def _get_user(self, username):
272
        path = 'users/%s' % urlutils.quote(str(project_name), '')
273
        response = self._api_request('GET', path)
274
        if response.status == 404:
275
            raise KeyError('no such user %s' % username)
276
        if response.status == 200:
277
            return json.loads(response.data)
278
        raise errors.InvalidHttpResponse(path, response.text)
279
280
    def _get_user_by_email(self, username):
281
        path = 'users?search=%s' % urlutils.quote(str(project_name), '')
282
        response = self._api_request('GET', path)
283
        if response.status == 404:
284
            raise KeyError('no such user %s' % username)
285
        if response.status == 200:
286
            ret = json.loads(response.data)
287
            if len(ret) != 1:
288
                raise ValueError('unexpected number of results; %r' % ret)
289
            return ret[0]
290
        raise errors.InvalidHttpResponse(path, response.text)
291
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
292
    def _get_project(self, project_name):
7359.1.2 by Jelmer Vernooij
Some fixes for gitlab API.
293
        path = 'projects/%s' % urlutils.quote(str(project_name), '')
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
294
        response = self._api_request('GET', path)
295
        if response.status == 404:
296
            raise NoSuchProject(project_name)
297
        if response.status == 200:
7296.10.8 by Jelmer Vernooij
Remove json attribute from Response object, consistent with urllib3 API.
298
            return json.loads(response.data)
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
299
        raise errors.InvalidHttpResponse(path, response.text)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
300
7380.1.2 by Jelmer Vernooij
Review comments.
301
    def _fork_project(self, project_name, timeout=50, interval=5):
7359.1.2 by Jelmer Vernooij
Some fixes for gitlab API.
302
        path = 'projects/%s/fork' % urlutils.quote(str(project_name), '')
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
303
        response = self._api_request('POST', path)
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
304
        if response.status not in (200, 201):
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
305
            raise errors.InvalidHttpResponse(path, response.text)
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
306
        # The response should be valid JSON, but let's ignore it
7397.1.1 by Jelmer Vernooij
Fix project forking.
307
        project = json.loads(response.data)
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
308
        # Spin and wait until import_status for new project
309
        # is complete.
7380.1.2 by Jelmer Vernooij
Review comments.
310
        deadline = time.time() + timeout
7397.1.1 by Jelmer Vernooij
Fix project forking.
311
        while project['import_status'] not in ('finished', 'none'):
7380.1.2 by Jelmer Vernooij
Review comments.
312
            mutter('import status is %s', project['import_status'])
313
            if time.time() > deadline:
314
                raise Exception('timeout waiting for project to become available')
315
            time.sleep(interval)
7397.1.1 by Jelmer Vernooij
Fix project forking.
316
            project = self._get_project(project['path_with_namespace'])
317
        return project
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
318
319
    def _get_logged_in_username(self):
320
        return self._current_user['username']
321
7408.1.1 by Jelmer Vernooij
Use paging to iterate over all gitlab pull requests.
322
    def _list_paged(self, path, parameters=None, per_page=None):
323
        if parameters is None:
324
            parameters = {}
325
        else:
326
            parameters = dict(parameters.items())
327
        if per_page:
7408.1.3 by Jelmer Vernooij
Support pagination for github.
328
            parameters['per_page'] = str(per_page)
7408.1.1 by Jelmer Vernooij
Use paging to iterate over all gitlab pull requests.
329
        page = "1"
330
        while page:
331
            parameters['page'] = page
332
            response = self._api_request(
333
                'GET', path + '?' +
334
                ';'.join(['%s=%s' % item for item in parameters.items()]))
335
            if response.status == 403:
336
                raise errors.PermissionDenied(response.text)
337
            if response.status != 200:
338
                raise errors.InvalidHttpResponse(path, response.text)
339
            page = response.getheader("X-Next-Page")
340
            for entry in json.loads(response.data):
341
                yield entry
342
7296.10.9 by Jelmer Vernooij
Fix method name spacing.
343
    def _list_merge_requests(self, owner=None, project=None, state=None):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
344
        if project is not None:
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
345
            path = 'projects/%s/merge_requests' % urlutils.quote(str(project), '')
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
346
        else:
347
            path = 'merge_requests'
348
        parameters = {}
349
        if state:
350
            parameters['state'] = state
351
        if owner:
352
            parameters['owner_id'] = urlutils.quote(owner, '')
7408.1.2 by Jelmer Vernooij
Set default page size to 50.
353
        return self._list_paged(path, parameters, per_page=DEFAULT_PAGE_SIZE)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
354
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
355
    def _update_merge_request(self, project_id, iid, mr):
356
        path = 'projects/%s/merge_requests/%s' % (
357
            urlutils.quote(str(project_id), ''), iid)
358
        response = self._api_request('PUT', path, fields=mr)
359
        if response.status == 200:
360
            return json.loads(response.data)
361
        raise errors.InvalidHttpResponse(path, response.text)
362
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
363
    def _create_mergerequest(
364
            self, title, source_project_id, target_project_id,
7296.10.3 by Jelmer Vernooij
More fixes.
365
            source_branch_name, target_branch_name, description,
366
            labels=None):
7359.1.2 by Jelmer Vernooij
Some fixes for gitlab API.
367
        path = 'projects/%s/merge_requests' % source_project_id
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
368
        fields = {
369
            'title': title,
370
            'source_branch': source_branch_name,
371
            'target_branch': target_branch_name,
372
            'target_project_id': target_project_id,
373
            'description': description,
374
            }
375
        if labels:
376
            fields['labels'] = labels
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
377
        response = self._api_request('POST', path, fields=fields)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
378
        if response.status == 403:
379
            raise errors.PermissionDenied(response.text)
380
        if response.status == 409:
381
            raise MergeProposalExists(self.source_branch.user_url)
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
382
        if response.status != 201:
383
            raise errors.InvalidHttpResponse(path, response.text)
7296.10.8 by Jelmer Vernooij
Remove json attribute from Response object, consistent with urllib3 API.
384
        return json.loads(response.data)
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
385
0.431.28 by Jelmer Vernooij
Implement Hoster.get_push_url.
386
    def get_push_url(self, branch):
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
387
        (host, project_name, branch_name) = parse_gitlab_branch_url(branch)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
388
        project = self._get_project(project_name)
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
389
        return gitlab_url_to_bzr_url(
7296.10.3 by Jelmer Vernooij
More fixes.
390
            project['ssh_url_to_repo'], branch_name)
0.431.28 by Jelmer Vernooij
Implement Hoster.get_push_url.
391
0.431.20 by Jelmer Vernooij
publish -> publish_derived.
392
    def publish_derived(self, local_branch, base_branch, name, project=None,
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
393
                        owner=None, revision_id=None, overwrite=False,
394
                        allow_lossy=True):
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
395
        (host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
396
        if owner is None:
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
397
            owner = self._get_logged_in_username()
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
398
        if project is None:
7296.10.3 by Jelmer Vernooij
More fixes.
399
            project = self._get_project(base_project)['path']
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
400
        try:
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
401
            target_project = self._get_project('%s/%s' % (owner, project))
402
        except NoSuchProject:
403
            target_project = self._fork_project(base_project)
7296.10.3 by Jelmer Vernooij
More fixes.
404
        remote_repo_url = git_url_to_bzr_url(target_project['ssh_url_to_repo'])
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
405
        remote_dir = controldir.ControlDir.open(remote_repo_url)
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
406
        try:
7211.13.7 by Jelmer Vernooij
Fix formatting.
407
            push_result = remote_dir.push_branch(
408
                local_branch, revision_id=revision_id, overwrite=overwrite,
409
                name=name)
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
410
        except errors.NoRoundtrippingSupport:
411
            if not allow_lossy:
412
                raise
7211.13.7 by Jelmer Vernooij
Fix formatting.
413
            push_result = remote_dir.push_branch(
414
                local_branch, revision_id=revision_id, overwrite=overwrite,
415
                name=name, lossy=True)
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
416
        public_url = gitlab_url_to_bzr_url(
7296.10.3 by Jelmer Vernooij
More fixes.
417
            target_project['http_url_to_repo'], name)
0.432.5 by Jelmer Vernooij
Fix publishing to gitlab.
418
        return push_result.target_branch, public_url
0.432.4 by Jelmer Vernooij
Some work on gitlab.
419
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
420
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
421
        (host, base_project, base_branch_name) = parse_gitlab_branch_url(base_branch)
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
422
        if owner is None:
7296.10.3 by Jelmer Vernooij
More fixes.
423
            owner = self._get_logged_in_username()
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
424
        if project is None:
7296.10.3 by Jelmer Vernooij
More fixes.
425
            project = self._get_project(base_project)['path']
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
426
        try:
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
427
            target_project = self._get_project('%s/%s' % (owner, project))
428
        except NoSuchProject:
429
            raise errors.NotBranchError('%s/%s/%s' % (self.base_url, owner, project))
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
430
        return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
7296.10.3 by Jelmer Vernooij
More fixes.
431
            target_project['ssh_url_to_repo'], name))
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
432
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
433
    def get_proposer(self, source_branch, target_branch):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
434
        return GitlabMergeProposalBuilder(self, source_branch, target_branch)
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
435
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
436
    def iter_proposals(self, source_branch, target_branch, status):
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
437
        (source_host, source_project_name, source_branch_name) = (
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
438
            parse_gitlab_branch_url(source_branch))
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
439
        (target_host, target_project_name, target_branch_name) = (
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
440
            parse_gitlab_branch_url(target_branch))
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
441
        if source_host != target_host:
442
            raise DifferentGitLabInstances(source_host, target_host)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
443
        source_project = self._get_project(source_project_name)
444
        target_project = self._get_project(target_project_name)
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
445
        state = mp_status_to_status(status)
7360.1.4 by Jelmer Vernooij
Fix retrieval of proposals from gitlab.
446
        for mr in self._list_merge_requests(
7296.10.3 by Jelmer Vernooij
More fixes.
447
                project=target_project['id'], state=state):
448
            if (mr['source_project_id'] != source_project['id'] or
449
                    mr['source_branch'] != source_branch_name or
450
                    mr['target_project_id'] != target_project['id'] or
451
                    mr['target_branch'] != target_branch_name):
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
452
                continue
453
            yield GitLabMergeProposal(self, mr)
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
454
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
455
    def hosts(self, branch):
456
        try:
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
457
            (host, project, branch_name) = parse_gitlab_branch_url(branch)
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
458
        except NotGitLabUrl:
459
            return False
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
460
        return (self.base_url == ('https://%s' % host))
461
462
    def check(self):
463
        response = self._api_request('GET', 'user')
464
        if response.status == 200:
7296.10.8 by Jelmer Vernooij
Remove json attribute from Response object, consistent with urllib3 API.
465
            self._current_user = json.loads(response.data)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
466
            return
7296.10.2 by Jelmer Vernooij
More fixes.
467
        if response == 401:
7296.10.8 by Jelmer Vernooij
Remove json attribute from Response object, consistent with urllib3 API.
468
            if json.loads(response.data) == {"message": "401 Unauthorized"}:
7296.10.2 by Jelmer Vernooij
More fixes.
469
                raise GitLabLoginMissing()
470
            else:
471
                raise GitlabLoginError(response.text)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
472
        raise UnsupportedHoster(url)
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
473
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
474
    @classmethod
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
475
    def probe_from_url(cls, url, possible_transports=None):
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
476
        try:
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
477
            (host, project) = parse_gitlab_url(url)
0.431.17 by Jelmer Vernooij
Try harder to avoid detecting any URL as a GitLab URL.
478
        except NotGitLabUrl:
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
479
            raise UnsupportedHoster(url)
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
480
        transport = get_transport(
481
            'https://%s' % host, possible_transports=possible_transports)
7359.1.2 by Jelmer Vernooij
Some fixes for gitlab API.
482
        credentials = get_credentials_by_url(transport.base)
483
        if credentials is not None:
484
            return cls(transport, credentials.get('private_token'))
485
        raise UnsupportedHoster(url)
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
486
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
487
    @classmethod
488
    def iter_instances(cls):
489
        for name, credentials in iter_tokens():
490
            if 'url' not in credentials:
491
                continue
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
492
            yield cls(
493
                get_transport(credentials['url']),
494
                private_token=credentials.get('private_token'))
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
495
0.431.66 by Jelmer Vernooij
Add support for status argument.
496
    def iter_my_proposals(self, status='open'):
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
497
        state = mp_status_to_status(status)
7296.10.9 by Jelmer Vernooij
Fix method name spacing.
498
        for mp in self._list_merge_requests(
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
499
                owner=self._get_logged_in_username(), state=state):
500
            yield GitLabMergeProposal(self, mp)
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
501
7296.9.1 by Jelmer Vernooij
Add 'brz land' subcommand.
502
    def get_proposal_by_url(self, url):
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
503
        try:
504
            (host, project, merge_id) = parse_gitlab_merge_request_url(url)
505
        except NotGitLabUrl:
506
            raise UnsupportedHoster(url)
7296.9.4 by Jelmer Vernooij
Fix dealing with non-gitlab sites.
507
        except NotMergeRequestUrl as e:
7360.1.4 by Jelmer Vernooij
Fix retrieval of proposals from gitlab.
508
            if self.base_url == ('https://%s' % e.host):
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
509
                raise
510
            else:
511
                raise UnsupportedHoster(url)
7360.1.4 by Jelmer Vernooij
Fix retrieval of proposals from gitlab.
512
        if self.base_url != ('https://%s' % host):
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
513
            raise UnsupportedHoster(url)
7360.1.4 by Jelmer Vernooij
Fix retrieval of proposals from gitlab.
514
        project = self._get_project(project)
7296.9.3 by Jelmer Vernooij
Support finding merge proposals by URL on GitLab instances.
515
        mr = project.mergerequests.get(merge_id)
516
        return GitLabMergeProposal(mr)
7296.9.1 by Jelmer Vernooij
Add 'brz land' subcommand.
517
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
518
0.432.2 by Jelmer Vernooij
Publish command sort of works.
519
class GitlabMergeProposalBuilder(MergeProposalBuilder):
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
520
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
521
    def __init__(self, gl, source_branch, target_branch):
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
522
        self.gl = gl
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
523
        self.source_branch = source_branch
524
        (self.source_host, self.source_project_name, self.source_branch_name) = (
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
525
            parse_gitlab_branch_url(source_branch))
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
526
        self.target_branch = target_branch
527
        (self.target_host, self.target_project_name, self.target_branch_name) = (
7268.12.1 by Jelmer Vernooij
Split out probe_from_url.
528
            parse_gitlab_branch_url(target_branch))
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
529
        if self.source_host != self.target_host:
530
            raise DifferentGitLabInstances(self.source_host, self.target_host)
531
532
    def get_infotext(self):
533
        """Determine the initial comment for the merge proposal."""
534
        info = []
535
        info.append("Gitlab instance: %s\n" % self.target_host)
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
536
        info.append("Source: %s\n" % self.source_branch.user_url)
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
537
        info.append("Target: %s\n" % self.target_branch.user_url)
538
        return ''.join(info)
539
540
    def get_initial_body(self):
541
        """Get a body for the proposal for the user to modify.
542
543
        :return: a str or None.
544
        """
545
        return None
546
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
547
    def create_proposal(self, description, reviewers=None, labels=None,
7296.8.1 by Jelmer Vernooij
Add commit-message option to 'brz propose'.
548
                        prerequisite_branch=None, commit_message=None):
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
549
        """Perform the submission."""
7296.8.1 by Jelmer Vernooij
Add commit-message option to 'brz propose'.
550
        # https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
551
        if prerequisite_branch is not None:
552
            raise PrerequisiteBranchUnsupported(self)
7296.8.1 by Jelmer Vernooij
Add commit-message option to 'brz propose'.
553
        # Note that commit_message is ignored, since Gitlab doesn't support it.
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
554
        source_project = self.gl._get_project(self.source_project_name)
555
        target_project = self.gl._get_project(self.target_project_name)
0.431.5 by Jelmer Vernooij
Initial work on gitlab support.
556
        # TODO(jelmer): Allow setting title explicitly
557
        title = description.splitlines()[0]
558
        # TODO(jelmer): Allow setting allow_collaboration field
559
        # TODO(jelmer): Allow setting milestone field
560
        # TODO(jelmer): Allow setting squash field
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
561
        kwargs = {
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
562
            'title': title,
7296.10.3 by Jelmer Vernooij
More fixes.
563
            'source_project_id': source_project['id'],
564
            'target_project_id': target_project['id'],
7371.4.4 by Jelmer Vernooij
Pull in more fixes from janitor.
565
            'source_branch_name': self.source_branch_name,
566
            'target_branch_name': self.target_branch_name,
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
567
            'description': description}
568
        if labels:
569
            kwargs['labels'] = ','.join(labels)
7381.5.1 by Jelmer Vernooij
Several more fixes for merge proposals. Add functions for reopening merge proposals.
570
        if reviewers:
571
            kwargs['assignee_ids'] = []
572
            for reviewer in reviewers:
573
                if '@' in reviewer:
574
                    user = self.gl._get_user_by_email(reviewer)
575
                else:
576
                    user = self.gl._get_user(reviewer)
577
                kwargs['assignee_ids'].append(user['id'])
7296.10.1 by Jelmer Vernooij
Initial work making gitlab just directly use ReST.
578
        merge_request = self.gl._create_mergerequest(**kwargs)
579
        return GitLabMergeProposal(self.gl, merge_request)
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
580
581
582
def register_gitlab_instance(shortname, url):
583
    """Register a gitlab instance.
584
585
    :param shortname: Short name (e.g. "gitlab")
586
    :param url: URL to the gitlab instance
587
    """
588
    from breezy.bugtracker import (
589
        tracker_registry,
590
        ProjectIntegerBugTracker,
591
        )
592
    tracker_registry.register(
593
        shortname, ProjectIntegerBugTracker(
594
            shortname, url + '/{project}/issues/{id}'))