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

  • Committer: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

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