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
26
from ...propose import (
36
branch as _mod_branch,
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 (
50
from launchpadlib import uris
52
from ...transport import get_transport
55
# TODO(jelmer): Make selection of launchpad staging a configuration option.
57
def status_to_lp_mp_statuses(status):
59
if status in ('open', 'all'):
64
'Code failed to merge',
66
if status in ('closed', 'all'):
67
statuses.extend(['Rejected', 'Superseded'])
68
if status in ('merged', 'all'):
69
statuses.append('Merged')
73
def plausible_launchpad_url(url):
76
if url.startswith('lp:'):
78
regex = re.compile(r'([a-z]*\+)*(bzr\+ssh|http|ssh|git|https)'
79
r'://(bazaar|git).*\.launchpad\.net')
80
return bool(regex.match(url))
83
class WebserviceFailure(Exception):
85
def __init__(self, message):
86
self.message = message
89
def _call_webservice(call, *args, **kwargs):
90
"""Make a call to the webservice, wrapping failures.
92
:param call: The call to make.
93
:param *args: *args for the call.
94
:param **kwargs: **kwargs for the call.
95
:return: The result of calling call(*args, *kwargs).
97
from lazr.restfulclient import errors as restful_errors
99
return call(*args, **kwargs)
100
except restful_errors.HTTPError as e:
102
for line in e.content.splitlines():
103
if line.startswith(b'Traceback (most recent call last):'):
105
error_lines.append(line)
106
raise WebserviceFailure(b''.join(error_lines))
109
class LaunchpadMergeProposal(MergeProposal):
111
def __init__(self, mp):
114
def get_source_branch_url(self):
115
if self._mp.source_branch:
116
return self._mp.source_branch.bzr_identity
118
return git_url_to_bzr_url(
119
self._mp.source_git_repository.git_identity,
120
ref=self._mp.source_git_path.encode('utf-8'))
122
def get_target_branch_url(self):
123
if self._mp.target_branch:
124
return self._mp.target_branch.bzr_identity
126
return git_url_to_bzr_url(
127
self._mp.target_git_repository.git_identity,
128
ref=self._mp.target_git_path.encode('utf-8'))
132
return lp_api.canonical_url(self._mp)
135
return (self._mp.queue_status == 'Merged')
138
return (self._mp.queue_status in ('Rejected', 'Superseded'))
141
self._mp.setStatus(status='Needs review')
143
def get_description(self):
144
return self._mp.description
146
def set_description(self, description):
147
self._mp.description = description
150
def get_commit_message(self):
151
return self._mp.commit_message
153
def set_commit_message(self, commit_message):
154
self._mp.commit_message = commit_message
158
self._mp.setStatus(status='Rejected')
160
def can_be_merged(self):
161
if not self._mp.preview_diff:
164
return not bool(self._mp.preview_diff.conflicts)
166
def get_merged_by(self):
167
merge_reporter = self._mp.merge_reporter
168
if merge_reporter is None:
170
return merge_reporter.name
172
def get_merged_at(self):
173
return self._mp.date_merged
175
def merge(self, commit_message=None):
176
target_branch = _mod_branch.Branch.open(
177
self.get_target_branch_url())
178
source_branch = _mod_branch.Branch.open(
179
self.get_source_branch_url())
180
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
182
# tree = target_branch.create_memorytree()
183
tmpdir = tempfile.mkdtemp()
185
tree = target_branch.create_checkout(
186
to_location=tmpdir, lightweight=True)
187
tree.merge_from_branch(source_branch)
188
tree.commit(commit_message or self._mp.commit_message)
190
shutil.rmtree(tmpdir)
193
class Launchpad(Hoster):
194
"""The Launchpad hosting service."""
198
# https://bugs.launchpad.net/launchpad/+bug/397676
199
supports_merge_proposal_labels = False
201
supports_merge_proposal_commit_message = True
203
supports_allow_collaboration = False
205
merge_proposal_description_format = 'plain'
207
def __init__(self, staging=False):
208
self._staging = staging
210
lp_base_url = uris.STAGING_SERVICE_ROOT
212
lp_base_url = uris.LPNET_SERVICE_ROOT
213
self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
217
return lp_api.uris.web_root_for_service_root(
218
str(self.launchpad._root_uri))
221
return "Launchpad(staging=%s)" % self._staging
223
def hosts(self, branch):
224
# TODO(jelmer): staging vs non-staging?
225
return plausible_launchpad_url(branch.user_url)
228
def probe_from_url(cls, url, possible_transports=None):
229
if plausible_launchpad_url(url):
231
raise UnsupportedHoster(url)
233
def _get_lp_git_ref_from_branch(self, branch):
234
url, params = urlutils.split_segment_parameters(branch.user_url)
235
(scheme, user, password, host, port, path) = urlutils.parse_url(
237
repo_lp = self.launchpad.git_repositories.getByPath(
238
path=path.strip('/'))
240
ref_path = params['ref']
242
branch_name = params.get('branch', branch.name)
244
ref_path = 'refs/heads/%s' % branch_name
246
ref_path = repo_lp.default_branch
247
ref_lp = repo_lp.getRefByPath(path=ref_path)
248
return (repo_lp, ref_lp)
250
def _get_lp_bzr_branch_from_branch(self, branch):
251
return self.launchpad.branches.getByUrl(
252
url=urlutils.unescape(branch.user_url))
254
def _get_derived_git_path(self, base_path, owner, project):
255
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
257
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
258
if project.startswith('~'):
259
project = '/'.join(base_path.split('/')[1:])
260
# TODO(jelmer): Surely there is a better way of creating one of these
262
return "~%s/%s" % (owner, project)
264
def _publish_git(self, local_branch, base_path, name, owner, project=None,
265
revision_id=None, overwrite=False, allow_lossy=True,
267
to_path = self._get_derived_git_path(base_path, owner, project)
268
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
270
dir_to = controldir.ControlDir.open_from_transport(to_transport)
271
except errors.NotBranchError:
272
# Didn't find anything
277
br_to = local_branch.create_clone_on_transport(
278
to_transport, revision_id=revision_id, name=name,
279
tag_selector=tag_selector)
280
except errors.NoRoundtrippingSupport:
281
br_to = local_branch.create_clone_on_transport(
282
to_transport, revision_id=revision_id, name=name,
283
lossy=True, tag_selector=tag_selector)
286
dir_to = dir_to.push_branch(
287
local_branch, revision_id, overwrite=overwrite, name=name,
288
tag_selector=tag_selector)
289
except errors.NoRoundtrippingSupport:
292
dir_to = dir_to.push_branch(
293
local_branch, revision_id, overwrite=overwrite, name=name,
294
lossy=True, tag_selector=tag_selector)
295
br_to = dir_to.target_branch
297
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
299
def _get_derived_bzr_path(self, base_branch, name, owner, project):
301
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
302
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
303
# TODO(jelmer): Surely there is a better way of creating one of these
305
return "~%s/%s/%s" % (owner, project, name)
307
def get_push_url(self, branch):
308
(vcs, user, password, path, params) = self._split_url(branch.user_url)
310
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
311
return branch_lp.bzr_identity
313
return urlutils.join_segment_parameters(
314
"git+ssh://git.launchpad.net/" + path, params)
318
def _publish_bzr(self, local_branch, base_branch, name, owner,
319
project=None, revision_id=None, overwrite=False,
320
allow_lossy=True, tag_selector=None):
321
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
322
to_transport = get_transport("lp:" + to_path)
324
dir_to = controldir.ControlDir.open_from_transport(to_transport)
325
except errors.NotBranchError:
326
# Didn't find anything
330
br_to = local_branch.create_clone_on_transport(
331
to_transport, revision_id=revision_id, tag_selector=tag_selector)
333
br_to = dir_to.push_branch(
334
local_branch, revision_id, overwrite=overwrite,
335
tag_selector=tag_selector).target_branch
336
return br_to, ("https://code.launchpad.net/" + to_path)
338
def _split_url(self, url):
339
url, params = urlutils.split_segment_parameters(url)
340
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
341
path = path.strip('/')
342
if host.startswith('bazaar.'):
344
elif host.startswith('git.'):
347
raise ValueError("unknown host %s" % host)
348
return (vcs, user, password, path, params)
350
def publish_derived(self, local_branch, base_branch, name, project=None,
351
owner=None, revision_id=None, overwrite=False,
352
allow_lossy=True, tag_selector=None):
353
"""Publish a branch to the site, derived from base_branch.
355
:param base_branch: branch to derive the new branch from
356
:param new_branch: branch to publish
357
:param name: Name of the new branch on the remote host
358
:param project: Optional project name
359
:param owner: Optional owner
360
:return: resulting branch
363
owner = self.launchpad.me.name
364
(base_vcs, base_user, base_password, base_path,
365
base_params) = self._split_url(base_branch.user_url)
366
# TODO(jelmer): Prevent publishing to development focus
367
if base_vcs == 'bzr':
368
return self._publish_bzr(
369
local_branch, base_branch, name, project=project, owner=owner,
370
revision_id=revision_id, overwrite=overwrite,
371
allow_lossy=allow_lossy, tag_selector=tag_selector)
372
elif base_vcs == 'git':
373
return self._publish_git(
374
local_branch, base_path, name, project=project, owner=owner,
375
revision_id=revision_id, overwrite=overwrite,
376
allow_lossy=allow_lossy, tag_selector=tag_selector)
378
raise AssertionError('not a valid Launchpad URL')
380
def get_derived_branch(self, base_branch, name, project=None, owner=None):
382
owner = self.launchpad.me.name
383
(base_vcs, base_user, base_password, base_path,
384
base_params) = self._split_url(base_branch.user_url)
385
if base_vcs == 'bzr':
386
to_path = self._get_derived_bzr_path(
387
base_branch, name, owner, project)
388
return _mod_branch.Branch.open("lp:" + to_path)
389
elif base_vcs == 'git':
390
to_path = self._get_derived_git_path(
391
base_path.strip('/'), owner, project)
392
to_url = urlutils.join_segment_parameters(
393
"git+ssh://git.launchpad.net/" + to_path,
395
return _mod_branch.Branch.open(to_url)
397
raise AssertionError('not a valid Launchpad URL')
399
def iter_proposals(self, source_branch, target_branch, status='open'):
400
(base_vcs, base_user, base_password, base_path,
401
base_params) = self._split_url(target_branch.user_url)
402
statuses = status_to_lp_mp_statuses(status)
403
if base_vcs == 'bzr':
404
target_branch_lp = self.launchpad.branches.getByUrl(
405
url=target_branch.user_url)
406
source_branch_lp = self.launchpad.branches.getByUrl(
407
url=source_branch.user_url)
408
for mp in target_branch_lp.getMergeProposals(status=statuses):
409
if mp.source_branch_link != source_branch_lp.self_link:
411
yield LaunchpadMergeProposal(mp)
412
elif base_vcs == 'git':
413
(source_repo_lp, source_branch_lp) = (
414
self._get_lp_git_ref_from_branch(source_branch))
415
(target_repo_lp, target_branch_lp) = (
416
self._get_lp_git_ref_from_branch(target_branch))
417
for mp in target_branch_lp.getMergeProposals(status=statuses):
418
if (target_branch_lp.path != mp.target_git_path or
419
target_repo_lp != mp.target_git_repository or
420
source_branch_lp.path != mp.source_git_path or
421
source_repo_lp != mp.source_git_repository):
423
yield LaunchpadMergeProposal(mp)
425
raise AssertionError('not a valid Launchpad URL')
427
def get_proposer(self, source_branch, target_branch):
428
(base_vcs, base_user, base_password, base_path,
429
base_params) = self._split_url(target_branch.user_url)
430
if base_vcs == 'bzr':
431
return LaunchpadBazaarMergeProposalBuilder(
432
self, source_branch, target_branch)
433
elif base_vcs == 'git':
434
return LaunchpadGitMergeProposalBuilder(
435
self, source_branch, target_branch)
437
raise AssertionError('not a valid Launchpad URL')
440
def iter_instances(cls):
443
def iter_my_proposals(self, status='open'):
444
statuses = status_to_lp_mp_statuses(status)
445
for mp in self.launchpad.me.getMergeProposals(status=statuses):
446
yield LaunchpadMergeProposal(mp)
448
def iter_my_forks(self):
449
# Launchpad doesn't really have the concept of "forks"
452
def get_proposal_by_url(self, url):
453
# Launchpad doesn't have a way to find a merge proposal by URL.
454
(scheme, user, password, host, port, path) = urlutils.parse_url(
456
LAUNCHPAD_CODE_DOMAINS = [
457
('code.%s' % domain) for domain in lp_uris.LAUNCHPAD_DOMAINS.values()]
458
if host not in LAUNCHPAD_CODE_DOMAINS:
459
raise UnsupportedHoster(url)
460
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
462
# See https://api.launchpad.net/devel/#branch_merge_proposal
464
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
465
api_url = str(self.launchpad._root_uri) + path
466
mp = self.launchpad.load(api_url)
467
return LaunchpadMergeProposal(mp)
470
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
472
def __init__(self, lp_host, source_branch, target_branch,
473
staging=None, approve=None, fixes=None):
476
:param source_branch: The branch to propose for merging.
477
:param target_branch: The branch to merge into.
478
:param staging: If True, propose the merge against staging instead of
480
:param approve: If True, mark the new proposal as approved immediately.
481
This is useful when a project permits some things to be approved
482
by the submitter (e.g. merges between release and deployment
485
self.lp_host = lp_host
486
self.launchpad = lp_host.launchpad
487
self.source_branch = source_branch
488
self.source_branch_lp = self.launchpad.branches.getByUrl(
489
url=source_branch.user_url)
490
if target_branch is None:
491
self.target_branch_lp = self.source_branch_lp.get_target()
492
self.target_branch = _mod_branch.Branch.open(
493
self.target_branch_lp.bzr_identity)
495
self.target_branch = target_branch
496
self.target_branch_lp = self.launchpad.branches.getByUrl(
497
url=target_branch.user_url)
498
self.approve = approve
501
def get_infotext(self):
502
"""Determine the initial comment for the merge proposal."""
503
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
504
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
507
def get_initial_body(self):
508
"""Get a body for the proposal for the user to modify.
510
:return: a str or None.
512
if not self.hooks['merge_proposal_body']:
515
def list_modified_files():
516
lca_tree = self.source_branch_lp.find_lca_tree(
517
self.target_branch_lp)
518
source_tree = self.source_branch.basis_tree()
519
files = modified_files(lca_tree, source_tree)
521
with self.target_branch.lock_read(), \
522
self.source_branch.lock_read():
524
for hook in self.hooks['merge_proposal_body']:
526
'target_branch': self.target_branch_lp.bzr_identity,
527
'modified_files_callback': list_modified_files,
532
def check_proposal(self):
533
"""Check that the submission is sensible."""
534
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
535
raise errors.BzrCommandError(
536
'Source and target branches must be different.')
537
for mp in self.source_branch_lp.landing_targets:
538
if mp.queue_status in ('Merged', 'Rejected'):
540
if mp.target_branch.self_link == self.target_branch_lp.self_link:
541
raise MergeProposalExists(lp_api.canonical_url(mp))
543
def approve_proposal(self, mp):
544
with self.source_branch.lock_read():
548
subject='', # Use the default subject.
549
content=u"Rubberstamp! Proposer approves of own proposal.")
550
_call_webservice(mp.setStatus, status=u'Approved',
551
revid=self.source_branch.last_revision())
553
def create_proposal(self, description, reviewers=None, labels=None,
554
prerequisite_branch=None, commit_message=None,
555
work_in_progress=False, allow_collaboration=False):
556
"""Perform the submission."""
558
raise LabelsUnsupported(self)
559
if prerequisite_branch is not None:
560
prereq = self.launchpad.branches.getByUrl(
561
url=prerequisite_branch.user_url)
564
if reviewers is None:
568
for reviewer in reviewers:
570
reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
572
reviewer_obj = self.launchpad.people[reviewer]
573
reviewer_objs.append(reviewer_obj)
575
mp = _call_webservice(
576
self.source_branch_lp.createMergeProposal,
577
target_branch=self.target_branch_lp,
578
prerequisite_branch=prereq,
579
initial_comment=description.strip(),
580
commit_message=commit_message,
581
needs_review=(not work_in_progress),
582
reviewers=[reviewer.self_link for reviewer in reviewer_objs],
583
review_types=['' for reviewer in reviewer_objs])
584
except WebserviceFailure as e:
586
if (b'There is already a branch merge proposal '
587
b'registered for branch ') in e.message:
588
raise MergeProposalExists(self.source_branch.user_url)
592
self.approve_proposal(mp)
594
if self.fixes.startswith('lp:'):
595
self.fixes = self.fixes[3:]
598
bug=self.launchpad.bugs[int(self.fixes)])
599
return LaunchpadMergeProposal(mp)
602
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
604
def __init__(self, lp_host, source_branch, target_branch,
605
staging=None, approve=None, fixes=None):
608
:param source_branch: The branch to propose for merging.
609
:param target_branch: The branch to merge into.
610
:param staging: If True, propose the merge against staging instead of
612
:param approve: If True, mark the new proposal as approved immediately.
613
This is useful when a project permits some things to be approved
614
by the submitter (e.g. merges between release and deployment
617
self.lp_host = lp_host
618
self.launchpad = lp_host.launchpad
619
self.source_branch = source_branch
620
(self.source_repo_lp,
621
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
623
if target_branch is None:
624
self.target_branch_lp = self.source_branch.get_target()
625
self.target_branch = _mod_branch.Branch.open(
626
self.target_branch_lp.git_https_url)
628
self.target_branch = target_branch
629
(self.target_repo_lp, self.target_branch_lp) = (
630
self.lp_host._get_lp_git_ref_from_branch(target_branch))
631
self.approve = approve
634
def get_infotext(self):
635
"""Determine the initial comment for the merge proposal."""
636
info = ["Source: %s\n" % self.source_branch.user_url]
637
info.append("Target: %s\n" % self.target_branch.user_url)
640
def get_initial_body(self):
641
"""Get a body for the proposal for the user to modify.
643
:return: a str or None.
645
if not self.hooks['merge_proposal_body']:
648
def list_modified_files():
649
lca_tree = self.source_branch_lp.find_lca_tree(
650
self.target_branch_lp)
651
source_tree = self.source_branch.basis_tree()
652
files = modified_files(lca_tree, source_tree)
654
with self.target_branch.lock_read(), \
655
self.source_branch.lock_read():
657
for hook in self.hooks['merge_proposal_body']:
659
'target_branch': self.target_branch,
660
'modified_files_callback': list_modified_files,
665
def check_proposal(self):
666
"""Check that the submission is sensible."""
667
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
668
raise errors.BzrCommandError(
669
'Source and target branches must be different.')
670
for mp in self.source_branch_lp.landing_targets:
671
if mp.queue_status in ('Merged', 'Rejected'):
673
if mp.target_branch.self_link == self.target_branch_lp.self_link:
674
raise MergeProposalExists(lp_api.canonical_url(mp))
676
def approve_proposal(self, mp):
677
with self.source_branch.lock_read():
681
subject='', # Use the default subject.
682
content=u"Rubberstamp! Proposer approves of own proposal.")
684
mp.setStatus, status=u'Approved',
685
revid=self.source_branch.last_revision())
687
def create_proposal(self, description, reviewers=None, labels=None,
688
prerequisite_branch=None, commit_message=None):
689
"""Perform the submission."""
691
raise LabelsUnsupported(self)
692
if prerequisite_branch is not None:
693
(prereq_repo_lp, prereq_branch_lp) = (
694
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
696
prereq_branch_lp = None
697
if reviewers is None:
700
mp = _call_webservice(
701
self.source_branch_lp.createMergeProposal,
702
merge_target=self.target_branch_lp,
703
merge_prerequisite=prereq_branch_lp,
704
initial_comment=description.strip(),
705
commit_message=commit_message,
707
reviewers=[self.launchpad.people[reviewer].self_link
708
for reviewer in reviewers],
709
review_types=[None for reviewer in reviewers])
710
except WebserviceFailure as e:
712
if ('There is already a branch merge proposal '
713
'registered for branch ') in e.message:
714
raise MergeProposalExists(self.source_branch.user_url)
717
self.approve_proposal(mp)
719
if self.fixes.startswith('lp:'):
720
self.fixes = self.fixes[3:]
723
bug=self.launchpad.bugs[int(self.fixes)])
724
return LaunchpadMergeProposal(mp)
727
def modified_files(old_tree, new_tree):
728
"""Return a list of paths in the new tree with modified contents."""
729
for change in new_tree.iter_changes(old_tree):
730
if change.changed_content and change.kind[1] == 'file':