/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/launchpad.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-05 01:40:59 UTC
  • mto: This revision was merged to the branch mainline in revision 7480.
  • Revision ID: jelmer@jelmer.uk-20200205014059-1jrhjaphw5vh9i7s
Fix Python 2.7 build.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2010, 2011 Canonical Ltd
 
2
# Copyright (C) 2018 Breezy Developers
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
"""Support for Launchpad."""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
import re
 
23
import shutil
 
24
import tempfile
 
25
 
 
26
from ...propose import (
 
27
    Hoster,
 
28
    LabelsUnsupported,
 
29
    MergeProposal,
 
30
    MergeProposalBuilder,
 
31
    MergeProposalExists,
 
32
    UnsupportedHoster,
 
33
    )
 
34
 
 
35
from ... import (
 
36
    branch as _mod_branch,
 
37
    controldir,
 
38
    errors,
 
39
    hooks,
 
40
    urlutils,
 
41
    )
 
42
from ...git.urls import git_url_to_bzr_url
 
43
from ...lazy_import import lazy_import
 
44
lazy_import(globals(), """
 
45
from breezy.plugins.launchpad import (
 
46
    lp_api,
 
47
    uris as lp_uris,
 
48
    )
 
49
 
 
50
from launchpadlib import uris
 
51
""")
 
52
from ...transport import get_transport
 
53
 
 
54
 
 
55
# TODO(jelmer): Make selection of launchpad staging a configuration option.
 
56
 
 
57
def status_to_lp_mp_statuses(status):
 
58
    statuses = []
 
59
    if status in ('open', 'all'):
 
60
        statuses.extend([
 
61
            'Work in progress',
 
62
            'Needs review',
 
63
            'Approved',
 
64
            'Code failed to merge',
 
65
            'Queued'])
 
66
    if status in ('closed', 'all'):
 
67
        statuses.extend(['Rejected', 'Superseded'])
 
68
    if status in ('merged', 'all'):
 
69
        statuses.append('Merged')
 
70
    return statuses
 
71
 
 
72
 
 
73
def plausible_launchpad_url(url):
 
74
    if url is None:
 
75
        return False
 
76
    if url.startswith('lp:'):
 
77
        return True
 
78
    regex = re.compile(r'([a-z]*\+)*(bzr\+ssh|http|ssh|git|https)'
 
79
                       r'://(bazaar|git).*\.launchpad\.net')
 
80
    return bool(regex.match(url))
 
81
 
 
82
 
 
83
class WebserviceFailure(Exception):
 
84
 
 
85
    def __init__(self, message):
 
86
        self.message = message
 
87
 
 
88
 
 
89
def _call_webservice(call, *args, **kwargs):
 
90
    """Make a call to the webservice, wrapping failures.
 
91
 
 
92
    :param call: The call to make.
 
93
    :param *args: *args for the call.
 
94
    :param **kwargs: **kwargs for the call.
 
95
    :return: The result of calling call(*args, *kwargs).
 
96
    """
 
97
    from lazr.restfulclient import errors as restful_errors
 
98
    try:
 
99
        return call(*args, **kwargs)
 
100
    except restful_errors.HTTPError as e:
 
101
        error_lines = []
 
102
        for line in e.content.splitlines():
 
103
            if line.startswith(b'Traceback (most recent call last):'):
 
104
                break
 
105
            error_lines.append(line)
 
106
        raise WebserviceFailure(b''.join(error_lines))
 
107
 
 
108
 
 
109
class LaunchpadMergeProposal(MergeProposal):
 
110
 
 
111
    def __init__(self, mp):
 
112
        self._mp = mp
 
113
 
 
114
    def get_source_branch_url(self):
 
115
        if self._mp.source_branch:
 
116
            return self._mp.source_branch.bzr_identity
 
117
        else:
 
118
            return git_url_to_bzr_url(
 
119
                self._mp.source_git_repository.git_identity,
 
120
                ref=self._mp.source_git_path.encode('utf-8'))
 
121
 
 
122
    def get_target_branch_url(self):
 
123
        if self._mp.target_branch:
 
124
            return self._mp.target_branch.bzr_identity
 
125
        else:
 
126
            return git_url_to_bzr_url(
 
127
                self._mp.target_git_repository.git_identity,
 
128
                ref=self._mp.target_git_path.encode('utf-8'))
 
129
 
 
130
    @property
 
131
    def url(self):
 
132
        return lp_api.canonical_url(self._mp)
 
133
 
 
134
    def is_merged(self):
 
135
        return (self._mp.queue_status == 'Merged')
 
136
 
 
137
    def is_closed(self):
 
138
        return (self._mp.queue_status in ('Rejected', 'Superseded'))
 
139
 
 
140
    def reopen(self):
 
141
        self._mp.setStatus(status='Needs review')
 
142
 
 
143
    def get_description(self):
 
144
        return self._mp.description
 
145
 
 
146
    def set_description(self, description):
 
147
        self._mp.description = description
 
148
        self._mp.lp_save()
 
149
 
 
150
    def get_commit_message(self):
 
151
        return self._mp.commit_message
 
152
 
 
153
    def set_commit_message(self, commit_message):
 
154
        self._mp.commit_message = commit_message
 
155
        self._mp.lp_save()
 
156
 
 
157
    def close(self):
 
158
        self._mp.setStatus(status='Rejected')
 
159
 
 
160
    def can_be_merged(self):
 
161
        if not self._mp.preview_diff:
 
162
            # Maybe?
 
163
            return True
 
164
        return not bool(self._mp.preview_diff.conflicts)
 
165
 
 
166
    def get_merged_by(self):
 
167
        merge_reporter = self._mp.merge_reporter
 
168
        if merge_reporter is None:
 
169
            return None
 
170
        return merge_reporter.name
 
171
 
 
172
    def get_merged_at(self):
 
173
        return self._mp.date_merged
 
174
 
 
175
    def merge(self, commit_message=None):
 
176
        target_branch = _mod_branch.Branch.open(
 
177
            self.get_target_branch_url())
 
178
        source_branch = _mod_branch.Branch.open(
 
179
            self.get_source_branch_url())
 
180
        # TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
 
181
        # support that yet.
 
182
        # tree = target_branch.create_memorytree()
 
183
        tmpdir = tempfile.mkdtemp()
 
184
        try:
 
185
            tree = target_branch.create_checkout(
 
186
                to_location=tmpdir, lightweight=True)
 
187
            tree.merge_from_branch(source_branch)
 
188
            tree.commit(commit_message or self._mp.commit_message)
 
189
        finally:
 
190
            shutil.rmtree(tmpdir)
 
191
 
 
192
 
 
193
class Launchpad(Hoster):
 
194
    """The Launchpad hosting service."""
 
195
 
 
196
    name = 'launchpad'
 
197
 
 
198
    # https://bugs.launchpad.net/launchpad/+bug/397676
 
199
    supports_merge_proposal_labels = False
 
200
 
 
201
    supports_merge_proposal_commit_message = True
 
202
 
 
203
    merge_proposal_description_format = 'plain'
 
204
 
 
205
    def __init__(self, staging=False):
 
206
        self._staging = staging
 
207
        if staging:
 
208
            lp_base_url = uris.STAGING_SERVICE_ROOT
 
209
        else:
 
210
            lp_base_url = uris.LPNET_SERVICE_ROOT
 
211
        self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
 
212
 
 
213
    @property
 
214
    def base_url(self):
 
215
        return lp_api.uris.web_root_for_service_root(
 
216
            str(self.launchpad._root_uri))
 
217
 
 
218
    def __repr__(self):
 
219
        return "Launchpad(staging=%s)" % self._staging
 
220
 
 
221
    def hosts(self, branch):
 
222
        # TODO(jelmer): staging vs non-staging?
 
223
        return plausible_launchpad_url(branch.user_url)
 
224
 
 
225
    @classmethod
 
226
    def probe_from_url(cls, url, possible_transports=None):
 
227
        if plausible_launchpad_url(url):
 
228
            return Launchpad()
 
229
        raise UnsupportedHoster(url)
 
230
 
 
231
    def _get_lp_git_ref_from_branch(self, branch):
 
232
        url, params = urlutils.split_segment_parameters(branch.user_url)
 
233
        (scheme, user, password, host, port, path) = urlutils.parse_url(
 
234
            url)
 
235
        repo_lp = self.launchpad.git_repositories.getByPath(
 
236
            path=path.strip('/'))
 
237
        try:
 
238
            ref_path = params['ref']
 
239
        except KeyError:
 
240
            branch_name = params.get('branch', branch.name)
 
241
            if branch_name:
 
242
                ref_path = 'refs/heads/%s' % branch_name
 
243
            else:
 
244
                ref_path = repo_lp.default_branch
 
245
        ref_lp = repo_lp.getRefByPath(path=ref_path)
 
246
        return (repo_lp, ref_lp)
 
247
 
 
248
    def _get_lp_bzr_branch_from_branch(self, branch):
 
249
        return self.launchpad.branches.getByUrl(
 
250
            url=urlutils.unescape(branch.user_url))
 
251
 
 
252
    def _get_derived_git_path(self, base_path, owner, project):
 
253
        base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
 
254
        if project is None:
 
255
            project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
 
256
        if project.startswith('~'):
 
257
            project = '/'.join(base_path.split('/')[1:])
 
258
        # TODO(jelmer): Surely there is a better way of creating one of these
 
259
        # URLs?
 
260
        return "~%s/%s" % (owner, project)
 
261
 
 
262
    def _publish_git(self, local_branch, base_path, name, owner, project=None,
 
263
                     revision_id=None, overwrite=False, allow_lossy=True):
 
264
        to_path = self._get_derived_git_path(base_path, owner, project)
 
265
        to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
 
266
        try:
 
267
            dir_to = controldir.ControlDir.open_from_transport(to_transport)
 
268
        except errors.NotBranchError:
 
269
            # Didn't find anything
 
270
            dir_to = None
 
271
 
 
272
        if dir_to is None:
 
273
            try:
 
274
                br_to = local_branch.create_clone_on_transport(
 
275
                    to_transport, revision_id=revision_id, name=name)
 
276
            except errors.NoRoundtrippingSupport:
 
277
                br_to = local_branch.create_clone_on_transport(
 
278
                    to_transport, revision_id=revision_id, name=name,
 
279
                    lossy=True)
 
280
        else:
 
281
            try:
 
282
                dir_to = dir_to.push_branch(
 
283
                    local_branch, revision_id, overwrite=overwrite, name=name)
 
284
            except errors.NoRoundtrippingSupport:
 
285
                if not allow_lossy:
 
286
                    raise
 
287
                dir_to = dir_to.push_branch(
 
288
                    local_branch, revision_id, overwrite=overwrite, name=name,
 
289
                    lossy=True)
 
290
            br_to = dir_to.target_branch
 
291
        return br_to, (
 
292
            "https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
 
293
 
 
294
    def _get_derived_bzr_path(self, base_branch, name, owner, project):
 
295
        if project is None:
 
296
            base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
 
297
            project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
 
298
        # TODO(jelmer): Surely there is a better way of creating one of these
 
299
        # URLs?
 
300
        return "~%s/%s/%s" % (owner, project, name)
 
301
 
 
302
    def get_push_url(self, branch):
 
303
        (vcs, user, password, path, params) = self._split_url(branch.user_url)
 
304
        if vcs == 'bzr':
 
305
            branch_lp = self._get_lp_bzr_branch_from_branch(branch)
 
306
            return branch_lp.bzr_identity
 
307
        elif vcs == 'git':
 
308
            return urlutils.join_segment_parameters(
 
309
                "git+ssh://git.launchpad.net/" + path, params)
 
310
        else:
 
311
            raise AssertionError
 
312
 
 
313
    def _publish_bzr(self, local_branch, base_branch, name, owner,
 
314
                     project=None, revision_id=None, overwrite=False,
 
315
                     allow_lossy=True):
 
316
        to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
 
317
        to_transport = get_transport("lp:" + to_path)
 
318
        try:
 
319
            dir_to = controldir.ControlDir.open_from_transport(to_transport)
 
320
        except errors.NotBranchError:
 
321
            # Didn't find anything
 
322
            dir_to = None
 
323
 
 
324
        if dir_to is None:
 
325
            br_to = local_branch.create_clone_on_transport(
 
326
                to_transport, revision_id=revision_id)
 
327
        else:
 
328
            br_to = dir_to.push_branch(
 
329
                local_branch, revision_id, overwrite=overwrite).target_branch
 
330
        return br_to, ("https://code.launchpad.net/" + to_path)
 
331
 
 
332
    def _split_url(self, url):
 
333
        url, params = urlutils.split_segment_parameters(url)
 
334
        (scheme, user, password, host, port, path) = urlutils.parse_url(url)
 
335
        path = path.strip('/')
 
336
        if host.startswith('bazaar.'):
 
337
            vcs = 'bzr'
 
338
        elif host.startswith('git.'):
 
339
            vcs = 'git'
 
340
        else:
 
341
            raise ValueError("unknown host %s" % host)
 
342
        return (vcs, user, password, path, params)
 
343
 
 
344
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
345
                        owner=None, revision_id=None, overwrite=False,
 
346
                        allow_lossy=True):
 
347
        """Publish a branch to the site, derived from base_branch.
 
348
 
 
349
        :param base_branch: branch to derive the new branch from
 
350
        :param new_branch: branch to publish
 
351
        :param name: Name of the new branch on the remote host
 
352
        :param project: Optional project name
 
353
        :param owner: Optional owner
 
354
        :return: resulting branch
 
355
        """
 
356
        if owner is None:
 
357
            owner = self.launchpad.me.name
 
358
        (base_vcs, base_user, base_password, base_path,
 
359
            base_params) = self._split_url(base_branch.user_url)
 
360
        # TODO(jelmer): Prevent publishing to development focus
 
361
        if base_vcs == 'bzr':
 
362
            return self._publish_bzr(
 
363
                local_branch, base_branch, name, project=project, owner=owner,
 
364
                revision_id=revision_id, overwrite=overwrite,
 
365
                allow_lossy=allow_lossy)
 
366
        elif base_vcs == 'git':
 
367
            return self._publish_git(
 
368
                local_branch, base_path, name, project=project, owner=owner,
 
369
                revision_id=revision_id, overwrite=overwrite,
 
370
                allow_lossy=allow_lossy)
 
371
        else:
 
372
            raise AssertionError('not a valid Launchpad URL')
 
373
 
 
374
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
375
        if owner is None:
 
376
            owner = self.launchpad.me.name
 
377
        (base_vcs, base_user, base_password, base_path,
 
378
            base_params) = self._split_url(base_branch.user_url)
 
379
        if base_vcs == 'bzr':
 
380
            to_path = self._get_derived_bzr_path(
 
381
                base_branch, name, owner, project)
 
382
            return _mod_branch.Branch.open("lp:" + to_path)
 
383
        elif base_vcs == 'git':
 
384
            to_path = self._get_derived_git_path(
 
385
                base_path.strip('/'), owner, project)
 
386
            to_url = urlutils.join_segment_parameters(
 
387
                "git+ssh://git.launchpad.net/" + to_path,
 
388
                {'branch': name})
 
389
            return _mod_branch.Branch.open(to_url)
 
390
        else:
 
391
            raise AssertionError('not a valid Launchpad URL')
 
392
 
 
393
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
394
        (base_vcs, base_user, base_password, base_path,
 
395
            base_params) = self._split_url(target_branch.user_url)
 
396
        statuses = status_to_lp_mp_statuses(status)
 
397
        if base_vcs == 'bzr':
 
398
            target_branch_lp = self.launchpad.branches.getByUrl(
 
399
                url=target_branch.user_url)
 
400
            source_branch_lp = self.launchpad.branches.getByUrl(
 
401
                url=source_branch.user_url)
 
402
            for mp in target_branch_lp.getMergeProposals(status=statuses):
 
403
                if mp.source_branch_link != source_branch_lp.self_link:
 
404
                    continue
 
405
                yield LaunchpadMergeProposal(mp)
 
406
        elif base_vcs == 'git':
 
407
            (source_repo_lp, source_branch_lp) = (
 
408
                self._get_lp_git_ref_from_branch(source_branch))
 
409
            (target_repo_lp, target_branch_lp) = (
 
410
                self._get_lp_git_ref_from_branch(target_branch))
 
411
            for mp in target_branch_lp.getMergeProposals(status=statuses):
 
412
                if (target_branch_lp.path != mp.target_git_path or
 
413
                        target_repo_lp != mp.target_git_repository or
 
414
                        source_branch_lp.path != mp.source_git_path or
 
415
                        source_repo_lp != mp.source_git_repository):
 
416
                    continue
 
417
                yield LaunchpadMergeProposal(mp)
 
418
        else:
 
419
            raise AssertionError('not a valid Launchpad URL')
 
420
 
 
421
    def get_proposer(self, source_branch, target_branch):
 
422
        (base_vcs, base_user, base_password, base_path,
 
423
            base_params) = self._split_url(target_branch.user_url)
 
424
        if base_vcs == 'bzr':
 
425
            return LaunchpadBazaarMergeProposalBuilder(
 
426
                self, source_branch, target_branch)
 
427
        elif base_vcs == 'git':
 
428
            return LaunchpadGitMergeProposalBuilder(
 
429
                self, source_branch, target_branch)
 
430
        else:
 
431
            raise AssertionError('not a valid Launchpad URL')
 
432
 
 
433
    @classmethod
 
434
    def iter_instances(cls):
 
435
        yield cls()
 
436
 
 
437
    def iter_my_proposals(self, status='open'):
 
438
        statuses = status_to_lp_mp_statuses(status)
 
439
        for mp in self.launchpad.me.getMergeProposals(status=statuses):
 
440
            yield LaunchpadMergeProposal(mp)
 
441
 
 
442
    def iter_my_forks(self):
 
443
        # Launchpad doesn't really have the concept of "forks"
 
444
        return iter([])
 
445
 
 
446
    def get_proposal_by_url(self, url):
 
447
        # Launchpad doesn't have a way to find a merge proposal by URL.
 
448
        (scheme, user, password, host, port, path) = urlutils.parse_url(
 
449
            url)
 
450
        LAUNCHPAD_CODE_DOMAINS = [
 
451
            ('code.%s' % domain) for domain in lp_uris.LAUNCHPAD_DOMAINS.values()]
 
452
        if host not in LAUNCHPAD_CODE_DOMAINS:
 
453
            raise UnsupportedHoster(url)
 
454
        # TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
 
455
        # UnsupportedHoster
 
456
        # See https://api.launchpad.net/devel/#branch_merge_proposal
 
457
        # the syntax is:
 
458
        # https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
 
459
        api_url = str(self.launchpad._root_uri) + path
 
460
        mp = self.launchpad.load(api_url)
 
461
        return LaunchpadMergeProposal(mp)
 
462
 
 
463
 
 
464
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
 
465
 
 
466
    def __init__(self, lp_host, source_branch, target_branch,
 
467
                 staging=None, approve=None, fixes=None):
 
468
        """Constructor.
 
469
 
 
470
        :param source_branch: The branch to propose for merging.
 
471
        :param target_branch: The branch to merge into.
 
472
        :param staging: If True, propose the merge against staging instead of
 
473
            production.
 
474
        :param approve: If True, mark the new proposal as approved immediately.
 
475
            This is useful when a project permits some things to be approved
 
476
            by the submitter (e.g. merges between release and deployment
 
477
            branches).
 
478
        """
 
479
        self.lp_host = lp_host
 
480
        self.launchpad = lp_host.launchpad
 
481
        self.source_branch = source_branch
 
482
        self.source_branch_lp = self.launchpad.branches.getByUrl(
 
483
            url=source_branch.user_url)
 
484
        if target_branch is None:
 
485
            self.target_branch_lp = self.source_branch_lp.get_target()
 
486
            self.target_branch = _mod_branch.Branch.open(
 
487
                self.target_branch_lp.bzr_identity)
 
488
        else:
 
489
            self.target_branch = target_branch
 
490
            self.target_branch_lp = self.launchpad.branches.getByUrl(
 
491
                url=target_branch.user_url)
 
492
        self.approve = approve
 
493
        self.fixes = fixes
 
494
 
 
495
    def get_infotext(self):
 
496
        """Determine the initial comment for the merge proposal."""
 
497
        info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
 
498
        info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
 
499
        return ''.join(info)
 
500
 
 
501
    def get_initial_body(self):
 
502
        """Get a body for the proposal for the user to modify.
 
503
 
 
504
        :return: a str or None.
 
505
        """
 
506
        if not self.hooks['merge_proposal_body']:
 
507
            return None
 
508
 
 
509
        def list_modified_files():
 
510
            lca_tree = self.source_branch_lp.find_lca_tree(
 
511
                self.target_branch_lp)
 
512
            source_tree = self.source_branch.basis_tree()
 
513
            files = modified_files(lca_tree, source_tree)
 
514
            return list(files)
 
515
        with self.target_branch.lock_read(), \
 
516
                self.source_branch.lock_read():
 
517
            body = None
 
518
            for hook in self.hooks['merge_proposal_body']:
 
519
                body = hook({
 
520
                    'target_branch': self.target_branch_lp.bzr_identity,
 
521
                    'modified_files_callback': list_modified_files,
 
522
                    'old_body': body,
 
523
                })
 
524
            return body
 
525
 
 
526
    def check_proposal(self):
 
527
        """Check that the submission is sensible."""
 
528
        if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
 
529
            raise errors.BzrCommandError(
 
530
                'Source and target branches must be different.')
 
531
        for mp in self.source_branch_lp.landing_targets:
 
532
            if mp.queue_status in ('Merged', 'Rejected'):
 
533
                continue
 
534
            if mp.target_branch.self_link == self.target_branch_lp.self_link:
 
535
                raise MergeProposalExists(lp_api.canonical_url(mp))
 
536
 
 
537
    def approve_proposal(self, mp):
 
538
        with self.source_branch.lock_read():
 
539
            _call_webservice(
 
540
                mp.createComment,
 
541
                vote=u'Approve',
 
542
                subject='',  # Use the default subject.
 
543
                content=u"Rubberstamp! Proposer approves of own proposal.")
 
544
            _call_webservice(mp.setStatus, status=u'Approved',
 
545
                             revid=self.source_branch.last_revision())
 
546
 
 
547
    def create_proposal(self, description, reviewers=None, labels=None,
 
548
                        prerequisite_branch=None, commit_message=None,
 
549
                        work_in_progress=False):
 
550
        """Perform the submission."""
 
551
        if labels:
 
552
            raise LabelsUnsupported(self)
 
553
        if prerequisite_branch is not None:
 
554
            prereq = self.launchpad.branches.getByUrl(
 
555
                url=prerequisite_branch.user_url)
 
556
        else:
 
557
            prereq = None
 
558
        if reviewers is None:
 
559
            reviewer_objs = []
 
560
        else:
 
561
            reviewer_objs = []
 
562
            for reviewer in reviewers:
 
563
                if '@' in reviewer:
 
564
                    reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
 
565
                else:
 
566
                    reviewer_obj = self.launchpad.people[reviewer]
 
567
                reviewer_objs.append(reviewer_obj)
 
568
        try:
 
569
            mp = _call_webservice(
 
570
                self.source_branch_lp.createMergeProposal,
 
571
                target_branch=self.target_branch_lp,
 
572
                prerequisite_branch=prereq,
 
573
                initial_comment=description.strip(),
 
574
                commit_message=commit_message,
 
575
                needs_review=(not work_in_progress),
 
576
                reviewers=[reviewer.self_link for reviewer in reviewer_objs],
 
577
                review_types=['' for reviewer in reviewer_objs])
 
578
        except WebserviceFailure as e:
 
579
            # Urgh.
 
580
            if (b'There is already a branch merge proposal '
 
581
                    b'registered for branch ') in e.message:
 
582
                raise MergeProposalExists(self.source_branch.user_url)
 
583
            raise
 
584
 
 
585
        if self.approve:
 
586
            self.approve_proposal(mp)
 
587
        if self.fixes:
 
588
            if self.fixes.startswith('lp:'):
 
589
                self.fixes = self.fixes[3:]
 
590
            _call_webservice(
 
591
                mp.linkBug,
 
592
                bug=self.launchpad.bugs[int(self.fixes)])
 
593
        return LaunchpadMergeProposal(mp)
 
594
 
 
595
 
 
596
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
 
597
 
 
598
    def __init__(self, lp_host, source_branch, target_branch,
 
599
                 staging=None, approve=None, fixes=None):
 
600
        """Constructor.
 
601
 
 
602
        :param source_branch: The branch to propose for merging.
 
603
        :param target_branch: The branch to merge into.
 
604
        :param staging: If True, propose the merge against staging instead of
 
605
            production.
 
606
        :param approve: If True, mark the new proposal as approved immediately.
 
607
            This is useful when a project permits some things to be approved
 
608
            by the submitter (e.g. merges between release and deployment
 
609
            branches).
 
610
        """
 
611
        self.lp_host = lp_host
 
612
        self.launchpad = lp_host.launchpad
 
613
        self.source_branch = source_branch
 
614
        (self.source_repo_lp,
 
615
            self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
 
616
                source_branch)
 
617
        if target_branch is None:
 
618
            self.target_branch_lp = self.source_branch.get_target()
 
619
            self.target_branch = _mod_branch.Branch.open(
 
620
                self.target_branch_lp.git_https_url)
 
621
        else:
 
622
            self.target_branch = target_branch
 
623
            (self.target_repo_lp, self.target_branch_lp) = (
 
624
                self.lp_host._get_lp_git_ref_from_branch(target_branch))
 
625
        self.approve = approve
 
626
        self.fixes = fixes
 
627
 
 
628
    def get_infotext(self):
 
629
        """Determine the initial comment for the merge proposal."""
 
630
        info = ["Source: %s\n" % self.source_branch.user_url]
 
631
        info.append("Target: %s\n" % self.target_branch.user_url)
 
632
        return ''.join(info)
 
633
 
 
634
    def get_initial_body(self):
 
635
        """Get a body for the proposal for the user to modify.
 
636
 
 
637
        :return: a str or None.
 
638
        """
 
639
        if not self.hooks['merge_proposal_body']:
 
640
            return None
 
641
 
 
642
        def list_modified_files():
 
643
            lca_tree = self.source_branch_lp.find_lca_tree(
 
644
                self.target_branch_lp)
 
645
            source_tree = self.source_branch.basis_tree()
 
646
            files = modified_files(lca_tree, source_tree)
 
647
            return list(files)
 
648
        with self.target_branch.lock_read(), \
 
649
                self.source_branch.lock_read():
 
650
            body = None
 
651
            for hook in self.hooks['merge_proposal_body']:
 
652
                body = hook({
 
653
                    'target_branch': self.target_branch,
 
654
                    'modified_files_callback': list_modified_files,
 
655
                    'old_body': body,
 
656
                })
 
657
            return body
 
658
 
 
659
    def check_proposal(self):
 
660
        """Check that the submission is sensible."""
 
661
        if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
 
662
            raise errors.BzrCommandError(
 
663
                'Source and target branches must be different.')
 
664
        for mp in self.source_branch_lp.landing_targets:
 
665
            if mp.queue_status in ('Merged', 'Rejected'):
 
666
                continue
 
667
            if mp.target_branch.self_link == self.target_branch_lp.self_link:
 
668
                raise MergeProposalExists(lp_api.canonical_url(mp))
 
669
 
 
670
    def approve_proposal(self, mp):
 
671
        with self.source_branch.lock_read():
 
672
            _call_webservice(
 
673
                mp.createComment,
 
674
                vote=u'Approve',
 
675
                subject='',  # Use the default subject.
 
676
                content=u"Rubberstamp! Proposer approves of own proposal.")
 
677
            _call_webservice(
 
678
                mp.setStatus, status=u'Approved',
 
679
                revid=self.source_branch.last_revision())
 
680
 
 
681
    def create_proposal(self, description, reviewers=None, labels=None,
 
682
                        prerequisite_branch=None, commit_message=None):
 
683
        """Perform the submission."""
 
684
        if labels:
 
685
            raise LabelsUnsupported(self)
 
686
        if prerequisite_branch is not None:
 
687
            (prereq_repo_lp, prereq_branch_lp) = (
 
688
                self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
 
689
        else:
 
690
            prereq_branch_lp = None
 
691
        if reviewers is None:
 
692
            reviewers = []
 
693
        try:
 
694
            mp = _call_webservice(
 
695
                self.source_branch_lp.createMergeProposal,
 
696
                merge_target=self.target_branch_lp,
 
697
                merge_prerequisite=prereq_branch_lp,
 
698
                initial_comment=description.strip(),
 
699
                commit_message=commit_message,
 
700
                needs_review=True,
 
701
                reviewers=[self.launchpad.people[reviewer].self_link
 
702
                           for reviewer in reviewers],
 
703
                review_types=[None for reviewer in reviewers])
 
704
        except WebserviceFailure as e:
 
705
            # Urgh.
 
706
            if ('There is already a branch merge proposal '
 
707
                    'registered for branch ') in e.message:
 
708
                raise MergeProposalExists(self.source_branch.user_url)
 
709
            raise
 
710
        if self.approve:
 
711
            self.approve_proposal(mp)
 
712
        if self.fixes:
 
713
            if self.fixes.startswith('lp:'):
 
714
                self.fixes = self.fixes[3:]
 
715
            _call_webservice(
 
716
                mp.linkBug,
 
717
                bug=self.launchpad.bugs[int(self.fixes)])
 
718
        return LaunchpadMergeProposal(mp)
 
719
 
 
720
 
 
721
def modified_files(old_tree, new_tree):
 
722
    """Return a list of paths in the new tree with modified contents."""
 
723
    for change in new_tree.iter_changes(old_tree):
 
724
        if change.changed_content and change.kind[1] == 'file':
 
725
            yield str(path)