/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: 2019-09-01 15:33:59 UTC
  • mto: This revision was merged to the branch mainline in revision 7404.
  • Revision ID: jelmer@jelmer.uk-20190901153359-9gl0ai0x5wuiv444
Rename init-repo to init-shared-repo.

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