/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-02-09 02:59:15 UTC
  • mto: This revision was merged to the branch mainline in revision 7286.
  • Revision ID: jelmer@jelmer.uk-20190209025915-dckbtruqe0zrd3dq
Add purpose argument.

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
from ... import (
 
22
    branch as _mod_branch,
 
23
    controldir,
 
24
    errors,
 
25
    urlutils,
 
26
    )
 
27
from ...config import AuthenticationConfig
 
28
from ...git.urls import git_url_to_bzr_url
 
29
from ...sixish import PY3
 
30
 
 
31
from .propose import (
 
32
    Hoster,
 
33
    MergeProposal,
 
34
    MergeProposalBuilder,
 
35
    MergeProposalExists,
 
36
    NoSuchProject,
 
37
    PrerequisiteBranchUnsupported,
 
38
    UnsupportedHoster,
 
39
    )
 
40
 
 
41
def mp_status_to_status(status):
 
42
    return {
 
43
        'all': 'all',
 
44
        'open': 'opened',
 
45
        'merged': 'merged',
 
46
        'closed': 'closed'}[status]
 
47
 
 
48
 
 
49
class NotGitLabUrl(errors.BzrError):
 
50
 
 
51
    _fmt = "Not a GitLab URL: %(url)s"
 
52
 
 
53
    def __init__(self, url):
 
54
        errors.BzrError.__init__(self)
 
55
        self.url = url
 
56
 
 
57
 
 
58
class DifferentGitLabInstances(errors.BzrError):
 
59
 
 
60
    _fmt = ("Can't create merge proposals across GitLab instances: "
 
61
            "%(source_host)s and %(target_host)s")
 
62
 
 
63
    def __init__(self, source_host, target_host):
 
64
        self.source_host = source_host
 
65
        self.target_host = target_host
 
66
 
 
67
 
 
68
class GitLabLoginMissing(errors.BzrError):
 
69
 
 
70
    _fmt = ("Please log into GitLab")
 
71
 
 
72
 
 
73
def default_config_path():
 
74
    from breezy.config import config_dir
 
75
    import os
 
76
    return os.path.join(config_dir(), 'gitlab.conf')
 
77
 
 
78
 
 
79
def store_gitlab_token(name, url, private_token):
 
80
    """Store a GitLab token in a configuration file."""
 
81
    import configparser
 
82
    config = configparser.ConfigParser()
 
83
    path = default_config_path()
 
84
    config.read([path])
 
85
    config.add_section(name)
 
86
    config[name]['url'] = url
 
87
    config[name]['private_token'] = private_token
 
88
    with open(path, 'w') as f:
 
89
        config.write(f)
 
90
 
 
91
 
 
92
def iter_tokens():
 
93
    import configparser
 
94
    from gitlab.config import _DEFAULT_FILES
 
95
    config = configparser.ConfigParser()
 
96
    config.read(_DEFAULT_FILES + [default_config_path()])
 
97
    for name, section in config.items():
 
98
        yield name, section
 
99
 
 
100
 
 
101
def connect_gitlab(host):
 
102
    from gitlab import Gitlab, GitlabGetError
 
103
    auth = AuthenticationConfig()
 
104
 
 
105
    url = 'https://%s' % host
 
106
    credentials = auth.get_credentials('https', host)
 
107
    if credentials is None:
 
108
        for name, section in iter_tokens():
 
109
            if section.get('url') == url:
 
110
                credentials = section
 
111
                break
 
112
        else:
 
113
            try:
 
114
                return Gitlab(url)
 
115
            except GitlabGetError:
 
116
                raise GitLabLoginMissing()
 
117
    else:
 
118
        credentials['url'] = url
 
119
    return Gitlab(**credentials)
 
120
 
 
121
 
 
122
def parse_gitlab_url(branch):
 
123
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
124
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
125
        url)
 
126
    if scheme not in ('git+ssh', 'https', 'http'):
 
127
        raise NotGitLabUrl(branch.user_url)
 
128
    if not host:
 
129
        raise NotGitLabUrl(branch.user_url)
 
130
    path = path.strip('/')
 
131
    if path.endswith('.git'):
 
132
        path = path[:-4]
 
133
    return host, path, branch.name
 
134
 
 
135
 
 
136
class GitLabMergeProposal(MergeProposal):
 
137
 
 
138
    def __init__(self, mr):
 
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._mr.save()
 
151
 
 
152
    def _branch_url_from_project(self, project_id, branch_name):
 
153
        project = self._mr.manager.gitlab.projects.get(project_id)
 
154
        return gitlab_url_to_bzr_url(project.http_url_to_repo, branch_name)
 
155
 
 
156
    def get_source_branch_url(self):
 
157
        return self._branch_url_from_project(
 
158
            self._mr.source_project_id, self._mr.source_branch)
 
159
 
 
160
    def get_target_branch_url(self):
 
161
        return self._branch_url_from_project(
 
162
            self._mr.target_project_id, self._mr.target_branch)
 
163
 
 
164
    def is_merged(self):
 
165
        return (self._mr.state == 'merged')
 
166
 
 
167
    def close(self):
 
168
        self._mr.state_event = 'close'
 
169
        self._mr.save()
 
170
 
 
171
 
 
172
def gitlab_url_to_bzr_url(url, name):
 
173
    if not PY3:
 
174
        name = name.encode('utf-8')
 
175
    return urlutils.join_segment_parameters(
 
176
        git_url_to_bzr_url(url), {"branch": name})
 
177
 
 
178
 
 
179
class GitLab(Hoster):
 
180
    """GitLab hoster implementation."""
 
181
 
 
182
    supports_merge_proposal_labels = True
 
183
 
 
184
    def __repr__(self):
 
185
        return "<GitLab(%r)>" % self.gl.url
 
186
 
 
187
    @property
 
188
    def base_url(self):
 
189
        return self.gl.url
 
190
 
 
191
    def __init__(self, gl):
 
192
        self.gl = gl
 
193
 
 
194
    def get_push_url(self, branch):
 
195
        (host, project_name, branch_name) = parse_gitlab_url(branch)
 
196
        project = self.gl.projects.get(project_name)
 
197
        return gitlab_url_to_bzr_url(
 
198
            project.ssh_url_to_repo, branch_name)
 
199
 
 
200
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
201
                        owner=None, revision_id=None, overwrite=False,
 
202
                        allow_lossy=True):
 
203
        import gitlab
 
204
        (host, base_project, base_branch_name) = parse_gitlab_url(base_branch)
 
205
        self.gl.auth()
 
206
        try:
 
207
            base_project = self.gl.projects.get(base_project)
 
208
        except gitlab.GitlabGetError as e:
 
209
            if e.response_code == 404:
 
210
                raise NoSuchProject(base_project)
 
211
            else:
 
212
                raise
 
213
        if owner is None:
 
214
            owner = self.gl.user.username
 
215
        if project is None:
 
216
            project = base_project.path
 
217
        try:
 
218
            target_project = self.gl.projects.get('%s/%s' % (owner, project))
 
219
        except gitlab.GitlabGetError as e:
 
220
            if e.response_code == 404:
 
221
                target_project = base_project.forks.create({})
 
222
            else:
 
223
                raise
 
224
        remote_repo_url = git_url_to_bzr_url(target_project.ssh_url_to_repo)
 
225
        remote_dir = controldir.ControlDir.open(remote_repo_url)
 
226
        try:
 
227
            push_result = remote_dir.push_branch(
 
228
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
229
                name=name)
 
230
        except errors.NoRoundtrippingSupport:
 
231
            if not allow_lossy:
 
232
                raise
 
233
            push_result = remote_dir.push_branch(
 
234
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
235
                name=name, lossy=True)
 
236
        public_url = gitlab_url_to_bzr_url(
 
237
            target_project.http_url_to_repo, name)
 
238
        return push_result.target_branch, public_url
 
239
 
 
240
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
241
        import gitlab
 
242
        (host, base_project, base_branch_name) = parse_gitlab_url(base_branch)
 
243
        self.gl.auth()
 
244
        try:
 
245
            base_project = self.gl.projects.get(base_project)
 
246
        except gitlab.GitlabGetError as e:
 
247
            if e.response_code == 404:
 
248
                raise NoSuchProject(base_project)
 
249
            else:
 
250
                raise
 
251
        if owner is None:
 
252
            owner = self.gl.user.username
 
253
        if project is None:
 
254
            project = base_project.path
 
255
        try:
 
256
            target_project = self.gl.projects.get('%s/%s' % (owner, project))
 
257
        except gitlab.GitlabGetError as e:
 
258
            if e.response_code == 404:
 
259
                raise errors.NotBranchError('%s/%s/%s' % (self.gl.url, owner, project))
 
260
            raise
 
261
        return _mod_branch.Branch.open(gitlab_url_to_bzr_url(
 
262
            target_project.ssh_url_to_repo, name))
 
263
 
 
264
    def get_proposer(self, source_branch, target_branch):
 
265
        return GitlabMergeProposalBuilder(self.gl, source_branch, target_branch)
 
266
 
 
267
    def iter_proposals(self, source_branch, target_branch, status):
 
268
        import gitlab
 
269
        (source_host, source_project_name, source_branch_name) = (
 
270
            parse_gitlab_url(source_branch))
 
271
        (target_host, target_project_name, target_branch_name) = (
 
272
            parse_gitlab_url(target_branch))
 
273
        if source_host != target_host:
 
274
            raise DifferentGitLabInstances(source_host, target_host)
 
275
        self.gl.auth()
 
276
        source_project = self.gl.projects.get(source_project_name)
 
277
        target_project = self.gl.projects.get(target_project_name)
 
278
        state = mp_status_to_status(status)
 
279
        try:
 
280
            for mr in target_project.mergerequests.list(state=state):
 
281
                if (mr.source_project_id != source_project.id or
 
282
                        mr.source_branch != source_branch_name or
 
283
                        mr.target_project_id != target_project.id or
 
284
                        mr.target_branch != target_branch_name):
 
285
                    continue
 
286
                yield GitLabMergeProposal(mr)
 
287
        except gitlab.GitlabListError as e:
 
288
            if e.response_code == 403:
 
289
                raise errors.PermissionDenied(e.error_message)
 
290
 
 
291
    def hosts(self, branch):
 
292
        try:
 
293
            (host, project, branch_name) = parse_gitlab_url(branch)
 
294
        except NotGitLabUrl:
 
295
            return False
 
296
        return (self.gl.url == ('https://%s' % host))
 
297
 
 
298
    @classmethod
 
299
    def probe(cls, branch):
 
300
        try:
 
301
            (host, project, branch_name) = parse_gitlab_url(branch)
 
302
        except NotGitLabUrl:
 
303
            raise UnsupportedHoster(branch)
 
304
        import gitlab
 
305
        import requests.exceptions
 
306
        try:
 
307
            gl = connect_gitlab(host)
 
308
            gl.auth()
 
309
        except requests.exceptions.SSLError:
 
310
            # Well, I guess it could be..
 
311
            raise UnsupportedHoster(branch)
 
312
        except gitlab.GitlabGetError:
 
313
            raise UnsupportedHoster(branch)
 
314
        except gitlab.GitlabHttpError as e:
 
315
            if e.response_code in (404, 405, 503):
 
316
                raise UnsupportedHoster(branch)
 
317
            else:
 
318
                raise
 
319
        return cls(gl)
 
320
 
 
321
    @classmethod
 
322
    def iter_instances(cls):
 
323
        from gitlab import Gitlab
 
324
        for name, credentials in iter_tokens():
 
325
            if 'url' not in credentials:
 
326
                continue
 
327
            gl = Gitlab(**credentials)
 
328
            yield cls(gl)
 
329
 
 
330
    def iter_my_proposals(self, status='open'):
 
331
        state = mp_status_to_status(status)
 
332
        self.gl.auth()
 
333
        for mp in self.gl.mergerequests.list(
 
334
                owner=self.gl.user.username, state=state):
 
335
            yield GitLabMergeProposal(mp)
 
336
 
 
337
 
 
338
class GitlabMergeProposalBuilder(MergeProposalBuilder):
 
339
 
 
340
    def __init__(self, gl, source_branch, target_branch):
 
341
        self.gl = gl
 
342
        self.source_branch = source_branch
 
343
        (self.source_host, self.source_project_name, self.source_branch_name) = (
 
344
            parse_gitlab_url(source_branch))
 
345
        self.target_branch = target_branch
 
346
        (self.target_host, self.target_project_name, self.target_branch_name) = (
 
347
            parse_gitlab_url(target_branch))
 
348
        if self.source_host != self.target_host:
 
349
            raise DifferentGitLabInstances(self.source_host, self.target_host)
 
350
 
 
351
    def get_infotext(self):
 
352
        """Determine the initial comment for the merge proposal."""
 
353
        info = []
 
354
        info.append("Gitlab instance: %s\n" % self.target_host)
 
355
        info.append("Source: %s\n" % self.source_branch.user_url)
 
356
        info.append("Target: %s\n" % self.target_branch.user_url)
 
357
        return ''.join(info)
 
358
 
 
359
    def get_initial_body(self):
 
360
        """Get a body for the proposal for the user to modify.
 
361
 
 
362
        :return: a str or None.
 
363
        """
 
364
        return None
 
365
 
 
366
    def create_proposal(self, description, reviewers=None, labels=None,
 
367
                        prerequisite_branch=None):
 
368
        """Perform the submission."""
 
369
        if prerequisite_branch is not None:
 
370
            raise PrerequisiteBranchUnsupported(self)
 
371
        import gitlab
 
372
        # TODO(jelmer): Support reviewers
 
373
        self.gl.auth()
 
374
        source_project = self.gl.projects.get(self.source_project_name)
 
375
        target_project = self.gl.projects.get(self.target_project_name)
 
376
        # TODO(jelmer): Allow setting title explicitly
 
377
        title = description.splitlines()[0]
 
378
        # TODO(jelmer): Allow setting allow_collaboration field
 
379
        # TODO(jelmer): Allow setting milestone field
 
380
        # TODO(jelmer): Allow setting squash field
 
381
        kwargs = {
 
382
            'title': title,
 
383
            'target_project_id': target_project.id,
 
384
            'source_branch': self.source_branch_name,
 
385
            'target_branch': self.target_branch_name,
 
386
            'description': description}
 
387
        if labels:
 
388
            kwargs['labels'] = ','.join(labels)
 
389
        try:
 
390
            merge_request = source_project.mergerequests.create(kwargs)
 
391
        except gitlab.GitlabCreateError as e:
 
392
            if e.response_code == 403:
 
393
                raise errors.PermissionDenied(e.error_message)
 
394
            if e.response_code == 409:
 
395
                raise MergeProposalExists(self.source_branch.user_url)
 
396
            raise
 
397
        return GitLabMergeProposal(merge_request)
 
398
 
 
399
 
 
400
def register_gitlab_instance(shortname, url):
 
401
    """Register a gitlab instance.
 
402
 
 
403
    :param shortname: Short name (e.g. "gitlab")
 
404
    :param url: URL to the gitlab instance
 
405
    """
 
406
    from breezy.bugtracker import (
 
407
        tracker_registry,
 
408
        ProjectIntegerBugTracker,
 
409
        )
 
410
    tracker_registry.register(
 
411
        shortname, ProjectIntegerBugTracker(
 
412
            shortname, url + '/{project}/issues/{id}'))