1
# Copyright (C) 2010, 2011 Canonical Ltd
2
# Copyright (C) 2018 Breezy Developers
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.
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.
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
18
"""Support for Launchpad."""
20
from __future__ import absolute_import
24
from .propose import (
34
branch as _mod_branch,
40
from ...git.refs import ref_to_branch_name
41
from ...lazy_import import lazy_import
42
lazy_import(globals(), """
43
from breezy.plugins.launchpad import (
47
from launchpadlib import uris
49
from ...transport import get_transport
52
# TODO(jelmer): Make selection of launchpad staging a configuration option.
54
def status_to_lp_mp_statuses(status):
56
if status in ('open', 'all'):
61
'Code failed to merge',
63
if status in ('closed', 'all'):
64
statuses.extend(['Rejected', 'Superseded'])
65
if status in ('merged', 'all'):
66
statuses.append('Merged')
70
def plausible_launchpad_url(url):
73
if url.startswith('lp:'):
75
regex = re.compile('([a-z]*\+)*(bzr\+ssh|http|ssh|git|https)'
76
'://(bazaar|git).*.launchpad.net')
77
return bool(regex.match(url))
80
class WebserviceFailure(Exception):
82
def __init__(self, message):
83
self.message = message
86
def _call_webservice(call, *args, **kwargs):
87
"""Make a call to the webservice, wrapping failures.
89
:param call: The call to make.
90
:param *args: *args for the call.
91
:param **kwargs: **kwargs for the call.
92
:return: The result of calling call(*args, *kwargs).
94
from lazr.restfulclient import errors as restful_errors
96
return call(*args, **kwargs)
97
except restful_errors.HTTPError as e:
99
for line in e.content.splitlines():
100
if line.startswith(b'Traceback (most recent call last):'):
102
error_lines.append(line)
103
raise WebserviceFailure(b''.join(error_lines))
106
class LaunchpadMergeProposal(MergeProposal):
108
def __init__(self, mp):
111
def get_source_branch_url(self):
112
if self._mp.source_branch:
113
return self._mp.source_branch.bzr_identity
115
branch_name = ref_to_branch_name(
116
self._mp.source_git_path.encode('utf-8'))
117
return urlutils.join_segment_parameters(
118
self._mp.source_git_repository.git_identity,
119
{"branch": branch_name})
121
def get_target_branch_url(self):
122
if self._mp.target_branch:
123
return self._mp.target_branch.bzr_identity
125
branch_name = ref_to_branch_name(
126
self._mp.target_git_path.encode('utf-8'))
127
return urlutils.join_segment_parameters(
128
self._mp.target_git_repository.git_identity,
129
{"branch": branch_name})
133
return lp_api.canonical_url(self._mp)
136
return (self._mp.queue_status == 'Merged')
138
def get_description(self):
139
return self._mp.description
141
def set_description(self, description):
142
self._mp.description = description
145
self._mp.setStatus(status='Rejected')
148
class Launchpad(Hoster):
149
"""The Launchpad hosting service."""
153
# https://bugs.launchpad.net/launchpad/+bug/397676
154
supports_merge_proposal_labels = False
156
def __init__(self, staging=False):
157
self._staging = staging
159
lp_base_url = uris.STAGING_SERVICE_ROOT
161
lp_base_url = uris.LPNET_SERVICE_ROOT
162
self.launchpad = lp_api.connect_launchpad(lp_base_url)
166
return lp_api.uris.web_root_for_service_root(
167
str(self.launchpad._root_uri))
170
return "Launchpad(staging=%s)" % self._staging
172
def hosts(self, branch):
173
# TODO(jelmer): staging vs non-staging?
174
return plausible_launchpad_url(branch.user_url)
177
def probe_from_url(cls, url):
178
if plausible_launchpad_url(url):
180
raise UnsupportedHoster(url)
182
def _get_lp_git_ref_from_branch(self, branch):
183
url, params = urlutils.split_segment_parameters(branch.user_url)
184
(scheme, user, password, host, port, path) = urlutils.parse_url(
186
repo_lp = self.launchpad.git_repositories.getByPath(
187
path=path.strip('/'))
189
ref_path = params['ref']
191
branch_name = params.get('branch', branch.name)
193
ref_path = 'refs/heads/%s' % branch_name
195
ref_path = repo_lp.default_branch
196
ref_lp = repo_lp.getRefByPath(path=ref_path)
197
return (repo_lp, ref_lp)
199
def _get_lp_bzr_branch_from_branch(self, branch):
200
return self.launchpad.branches.getByUrl(
201
url=urlutils.unescape(branch.user_url))
203
def _get_derived_git_path(self, base_path, owner, project):
204
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
206
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
207
if project.startswith('~'):
208
project = '/'.join(base_path.split('/')[1:])
209
# TODO(jelmer): Surely there is a better way of creating one of these
211
return "~%s/%s" % (owner, project)
213
def _publish_git(self, local_branch, base_path, name, owner, project=None,
214
revision_id=None, overwrite=False, allow_lossy=True):
215
to_path = self._get_derived_git_path(base_path, owner, project)
216
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
218
dir_to = controldir.ControlDir.open_from_transport(to_transport)
219
except errors.NotBranchError:
220
# Didn't find anything
225
br_to = local_branch.create_clone_on_transport(
226
to_transport, revision_id=revision_id, name=name)
227
except errors.NoRoundtrippingSupport:
228
br_to = local_branch.create_clone_on_transport(
229
to_transport, revision_id=revision_id, name=name,
233
dir_to = dir_to.push_branch(
234
local_branch, revision_id, overwrite=overwrite, name=name)
235
except errors.NoRoundtrippingSupport:
238
dir_to = dir_to.push_branch(
239
local_branch, revision_id, overwrite=overwrite, name=name,
241
br_to = dir_to.target_branch
243
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
245
def _get_derived_bzr_path(self, base_branch, name, owner, project):
247
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
248
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
249
# TODO(jelmer): Surely there is a better way of creating one of these
251
return "~%s/%s/%s" % (owner, project, name)
253
def get_push_url(self, branch):
254
(vcs, user, password, path, params) = self._split_url(branch.user_url)
256
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
257
return branch_lp.bzr_identity
259
return urlutils.join_segment_parameters(
260
"git+ssh://git.launchpad.net/" + path, params)
264
def _publish_bzr(self, local_branch, base_branch, name, owner,
265
project=None, revision_id=None, overwrite=False,
267
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
268
to_transport = get_transport("lp:" + to_path)
270
dir_to = controldir.ControlDir.open_from_transport(to_transport)
271
except errors.NotBranchError:
272
# Didn't find anything
276
br_to = local_branch.create_clone_on_transport(
277
to_transport, revision_id=revision_id)
279
br_to = dir_to.push_branch(
280
local_branch, revision_id, overwrite=overwrite).target_branch
281
return br_to, ("https://code.launchpad.net/" + to_path)
283
def _split_url(self, url):
284
url, params = urlutils.split_segment_parameters(url)
285
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
286
path = path.strip('/')
287
if host.startswith('bazaar.'):
289
elif host.startswith('git.'):
292
raise ValueError("unknown host %s" % host)
293
return (vcs, user, password, path, params)
295
def publish_derived(self, local_branch, base_branch, name, project=None,
296
owner=None, revision_id=None, overwrite=False,
298
"""Publish a branch to the site, derived from base_branch.
300
:param base_branch: branch to derive the new branch from
301
:param new_branch: branch to publish
302
:param name: Name of the new branch on the remote host
303
:param project: Optional project name
304
:param owner: Optional owner
305
:return: resulting branch
308
owner = self.launchpad.me.name
309
(base_vcs, base_user, base_password, base_path,
310
base_params) = self._split_url(base_branch.user_url)
311
# TODO(jelmer): Prevent publishing to development focus
312
if base_vcs == 'bzr':
313
return self._publish_bzr(
314
local_branch, base_branch, name, project=project, owner=owner,
315
revision_id=revision_id, overwrite=overwrite,
316
allow_lossy=allow_lossy)
317
elif base_vcs == 'git':
318
return self._publish_git(
319
local_branch, base_path, name, project=project, owner=owner,
320
revision_id=revision_id, overwrite=overwrite,
321
allow_lossy=allow_lossy)
323
raise AssertionError('not a valid Launchpad URL')
325
def get_derived_branch(self, base_branch, name, project=None, owner=None):
327
owner = self.launchpad.me.name
328
(base_vcs, base_user, base_password, base_path,
329
base_params) = self._split_url(base_branch.user_url)
330
if base_vcs == 'bzr':
331
to_path = self._get_derived_bzr_path(
332
base_branch, name, owner, project)
333
return _mod_branch.Branch.open("lp:" + to_path)
334
elif base_vcs == 'git':
335
to_path = self._get_derived_git_path(
336
base_path.strip('/'), owner, project)
337
to_url = urlutils.join_segment_parameters(
338
"git+ssh://git.launchpad.net/" + to_path,
340
return _mod_branch.Branch.open(to_url)
342
raise AssertionError('not a valid Launchpad URL')
344
def iter_proposals(self, source_branch, target_branch, status='open'):
345
(base_vcs, base_user, base_password, base_path,
346
base_params) = self._split_url(target_branch.user_url)
347
statuses = status_to_lp_mp_statuses(status)
348
if base_vcs == 'bzr':
349
target_branch_lp = self.launchpad.branches.getByUrl(
350
url=target_branch.user_url)
351
source_branch_lp = self.launchpad.branches.getByUrl(
352
url=source_branch.user_url)
353
for mp in target_branch_lp.getMergeProposals(status=statuses):
354
if mp.source_branch_link != source_branch_lp.self_link:
356
yield LaunchpadMergeProposal(mp)
357
elif base_vcs == 'git':
358
(source_repo_lp, source_branch_lp) = (
359
self._get_lp_git_ref_from_branch(source_branch))
360
(target_repo_lp, target_branch_lp) = (
361
self._get_lp_git_ref_from_branch(target_branch))
362
for mp in target_branch_lp.getMergeProposals(status=statuses):
363
if (target_branch_lp.path != mp.target_git_path or
364
target_repo_lp != mp.target_git_repository or
365
source_branch_lp.path != mp.source_git_path or
366
source_repo_lp != mp.source_git_repository):
368
yield LaunchpadMergeProposal(mp)
370
raise AssertionError('not a valid Launchpad URL')
372
def get_proposer(self, source_branch, target_branch):
373
(base_vcs, base_user, base_password, base_path,
374
base_params) = self._split_url(target_branch.user_url)
375
if base_vcs == 'bzr':
376
return LaunchpadBazaarMergeProposalBuilder(
377
self, source_branch, target_branch)
378
elif base_vcs == 'git':
379
return LaunchpadGitMergeProposalBuilder(
380
self, source_branch, target_branch)
382
raise AssertionError('not a valid Launchpad URL')
385
def iter_instances(cls):
388
def iter_my_proposals(self, status='open'):
389
statuses = status_to_lp_mp_statuses(status)
390
for mp in self.launchpad.me.getMergeProposals(status=statuses):
391
yield LaunchpadMergeProposal(mp)
394
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
396
def __init__(self, lp_host, source_branch, target_branch, message=None,
397
staging=None, approve=None, fixes=None):
400
:param source_branch: The branch to propose for merging.
401
:param target_branch: The branch to merge into.
402
:param message: The commit message to use. (May be None.)
403
:param staging: If True, propose the merge against staging instead of
405
:param approve: If True, mark the new proposal as approved immediately.
406
This is useful when a project permits some things to be approved
407
by the submitter (e.g. merges between release and deployment
410
self.lp_host = lp_host
411
self.launchpad = lp_host.launchpad
412
self.source_branch = source_branch
413
self.source_branch_lp = self.launchpad.branches.getByUrl(
414
url=source_branch.user_url)
415
if target_branch is None:
416
self.target_branch_lp = self.source_branch_lp.get_target()
417
self.target_branch = _mod_branch.Branch.open(
418
self.target_branch_lp.bzr_identity)
420
self.target_branch = target_branch
421
self.target_branch_lp = self.launchpad.branches.getByUrl(
422
url=target_branch.user_url)
423
self.commit_message = message
424
self.approve = approve
427
def get_infotext(self):
428
"""Determine the initial comment for the merge proposal."""
429
if self.commit_message is not None:
430
return self.commit_message.strip().encode('utf-8')
431
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
432
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
435
def get_initial_body(self):
436
"""Get a body for the proposal for the user to modify.
438
:return: a str or None.
440
if not self.hooks['merge_proposal_body']:
443
def list_modified_files():
444
lca_tree = self.source_branch_lp.find_lca_tree(
445
self.target_branch_lp)
446
source_tree = self.source_branch.basis_tree()
447
files = modified_files(lca_tree, source_tree)
449
with self.target_branch.lock_read(), \
450
self.source_branch.lock_read():
452
for hook in self.hooks['merge_proposal_body']:
454
'target_branch': self.target_branch_lp.bzr_identity,
455
'modified_files_callback': list_modified_files,
460
def check_proposal(self):
461
"""Check that the submission is sensible."""
462
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
463
raise errors.BzrCommandError(
464
'Source and target branches must be different.')
465
for mp in self.source_branch_lp.landing_targets:
466
if mp.queue_status in ('Merged', 'Rejected'):
468
if mp.target_branch.self_link == self.target_branch_lp.self_link:
469
raise MergeProposalExists(lp_api.canonical_url(mp))
471
def approve_proposal(self, mp):
472
with self.source_branch.lock_read():
476
subject='', # Use the default subject.
477
content=u"Rubberstamp! Proposer approves of own proposal.")
478
_call_webservice(mp.setStatus, status=u'Approved',
479
revid=self.source_branch.last_revision())
481
def create_proposal(self, description, reviewers=None, labels=None,
482
prerequisite_branch=None):
483
"""Perform the submission."""
485
raise LabelsUnsupported()
486
if prerequisite_branch is not None:
487
prereq = self.launchpad.branches.getByUrl(
488
url=prerequisite_branch.user_url)
491
if reviewers is None:
494
mp = _call_webservice(
495
self.source_branch_lp.createMergeProposal,
496
target_branch=self.target_branch_lp,
497
prerequisite_branch=prereq,
498
initial_comment=description.strip(),
499
commit_message=self.commit_message,
500
reviewers=[self.launchpad.people[reviewer].self_link
501
for reviewer in reviewers],
502
review_types=[None for reviewer in reviewers])
503
except WebserviceFailure as e:
505
if (b'There is already a branch merge proposal '
506
b'registered for branch ') in e.message:
507
raise MergeProposalExists(self.source_branch.user_url)
511
self.approve_proposal(mp)
513
if self.fixes.startswith('lp:'):
514
self.fixes = self.fixes[3:]
517
bug=self.launchpad.bugs[int(self.fixes)])
518
return LaunchpadMergeProposal(mp)
521
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
523
def __init__(self, lp_host, source_branch, target_branch, message=None,
524
staging=None, approve=None, fixes=None):
527
:param source_branch: The branch to propose for merging.
528
:param target_branch: The branch to merge into.
529
:param message: The commit message to use. (May be None.)
530
:param staging: If True, propose the merge against staging instead of
532
:param approve: If True, mark the new proposal as approved immediately.
533
This is useful when a project permits some things to be approved
534
by the submitter (e.g. merges between release and deployment
537
self.lp_host = lp_host
538
self.launchpad = lp_host.launchpad
539
self.source_branch = source_branch
540
(self.source_repo_lp,
541
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
543
if target_branch is None:
544
self.target_branch_lp = self.source_branch.get_target()
545
self.target_branch = _mod_branch.Branch.open(
546
self.target_branch_lp.git_https_url)
548
self.target_branch = target_branch
549
(self.target_repo_lp, self.target_branch_lp) = (
550
self.lp_host._get_lp_git_ref_from_branch(target_branch))
551
self.commit_message = message
552
self.approve = approve
555
def get_infotext(self):
556
"""Determine the initial comment for the merge proposal."""
557
if self.commit_message is not None:
558
return self.commit_message.strip().encode('utf-8')
559
info = ["Source: %s\n" % self.source_branch.user_url]
560
info.append("Target: %s\n" % self.target_branch.user_url)
563
def get_initial_body(self):
564
"""Get a body for the proposal for the user to modify.
566
:return: a str or None.
568
if not self.hooks['merge_proposal_body']:
571
def list_modified_files():
572
lca_tree = self.source_branch_lp.find_lca_tree(
573
self.target_branch_lp)
574
source_tree = self.source_branch.basis_tree()
575
files = modified_files(lca_tree, source_tree)
577
with self.target_branch.lock_read(), \
578
self.source_branch.lock_read():
580
for hook in self.hooks['merge_proposal_body']:
582
'target_branch': self.target_branch,
583
'modified_files_callback': list_modified_files,
588
def check_proposal(self):
589
"""Check that the submission is sensible."""
590
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
591
raise errors.BzrCommandError(
592
'Source and target branches must be different.')
593
for mp in self.source_branch_lp.landing_targets:
594
if mp.queue_status in ('Merged', 'Rejected'):
596
if mp.target_branch.self_link == self.target_branch_lp.self_link:
597
raise MergeProposalExists(lp_api.canonical_url(mp))
599
def approve_proposal(self, mp):
600
with self.source_branch.lock_read():
604
subject='', # Use the default subject.
605
content=u"Rubberstamp! Proposer approves of own proposal.")
607
mp.setStatus, status=u'Approved',
608
revid=self.source_branch.last_revision())
610
def create_proposal(self, description, reviewers=None, labels=None,
611
prerequisite_branch=None):
612
"""Perform the submission."""
614
raise LabelsUnsupported()
615
if prerequisite_branch is not None:
616
(prereq_repo_lp, prereq_branch_lp) = (
617
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
619
prereq_branch_lp = None
620
if reviewers is None:
623
mp = _call_webservice(
624
self.source_branch_lp.createMergeProposal,
625
merge_target=self.target_branch_lp,
626
merge_prerequisite=prereq_branch_lp,
627
initial_comment=description.strip(),
628
commit_message=self.commit_message,
630
reviewers=[self.launchpad.people[reviewer].self_link
631
for reviewer in reviewers],
632
review_types=[None for reviewer in reviewers])
633
except WebserviceFailure as e:
635
if ('There is already a branch merge proposal '
636
'registered for branch ') in e.message:
637
raise MergeProposalExists(self.source_branch.user_url)
640
self.approve_proposal(mp)
642
if self.fixes.startswith('lp:'):
643
self.fixes = self.fixes[3:]
646
bug=self.launchpad.bugs[int(self.fixes)])
647
return LaunchpadMergeProposal(mp)
650
def modified_files(old_tree, new_tree):
651
"""Return a list of paths in the new tree with modified contents."""
652
for f, (op, path), c, v, p, n, (ok, k), e in new_tree.iter_changes(
654
if c and k == 'file':