/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-01-19 15:14:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7455.
  • Revision ID: jelmer@jelmer.uk-20200119151416-f2x9y9rtvwxndr2l
Don't show submodules that are not checked out as deltas.

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