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."""
24
from ...propose import (
34
branch as _mod_branch,
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 (
48
from launchpadlib import uris
50
from ...transport import get_transport
53
# TODO(jelmer): Make selection of launchpad staging a configuration option.
55
def status_to_lp_mp_statuses(status):
57
if status in ('open', 'all'):
62
'Code failed to merge',
64
if status in ('closed', 'all'):
65
statuses.extend(['Rejected', 'Superseded'])
66
if status in ('merged', 'all'):
67
statuses.append('Merged')
71
def plausible_launchpad_url(url):
74
if url.startswith('lp:'):
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))
81
class WebserviceFailure(Exception):
83
def __init__(self, message):
84
self.message = message
87
def _call_webservice(call, *args, **kwargs):
88
"""Make a call to the webservice, wrapping failures.
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).
95
from lazr.restfulclient import errors as restful_errors
97
return call(*args, **kwargs)
98
except restful_errors.HTTPError as e:
100
for line in e.content.splitlines():
101
if line.startswith(b'Traceback (most recent call last):'):
103
error_lines.append(line)
104
raise WebserviceFailure(b''.join(error_lines))
107
class LaunchpadMergeProposal(MergeProposal):
109
def __init__(self, mp):
112
def get_source_branch_url(self):
113
if self._mp.source_branch:
114
return self._mp.source_branch.bzr_identity
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'))
120
def get_target_branch_url(self):
121
if self._mp.target_branch:
122
return self._mp.target_branch.bzr_identity
124
return git_url_to_bzr_url(
125
self._mp.target_git_repository.git_identity,
126
ref=self._mp.target_git_path.encode('utf-8'))
130
return lp_api.canonical_url(self._mp)
133
return (self._mp.queue_status == 'Merged')
136
return (self._mp.queue_status in ('Rejected', 'Superseded'))
139
self._mp.setStatus(status='Needs review')
141
def get_description(self):
142
return self._mp.description
144
def set_description(self, description):
145
self._mp.description = description
148
def get_commit_message(self):
149
return self._mp.commit_message
151
def set_commit_message(self, commit_message):
152
self._mp.commit_message = commit_message
156
self._mp.setStatus(status='Rejected')
158
def can_be_merged(self):
159
if not self._mp.preview_diff:
162
return not bool(self._mp.preview_diff.conflicts)
164
def get_merged_by(self):
165
merge_reporter = self._mp.merge_reporter
166
if merge_reporter is None:
168
return merge_reporter.name
170
def get_merged_at(self):
171
return self._mp.date_merged
173
def merge(self, commit_message=None):
174
target_branch = _mod_branch.Branch.open(
175
self.get_target_branch_url())
176
source_branch = _mod_branch.Branch.open(
177
self.get_source_branch_url())
178
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
180
# tree = target_branch.create_memorytree()
181
tmpdir = tempfile.mkdtemp()
183
tree = target_branch.create_checkout(
184
to_location=tmpdir, lightweight=True)
185
tree.merge_from_branch(source_branch)
186
tree.commit(commit_message or self._mp.commit_message)
188
shutil.rmtree(tmpdir)
191
class Launchpad(Hoster):
192
"""The Launchpad hosting service."""
196
# https://bugs.launchpad.net/launchpad/+bug/397676
197
supports_merge_proposal_labels = False
199
supports_merge_proposal_commit_message = True
201
supports_allow_collaboration = False
203
merge_proposal_description_format = 'plain'
205
def __init__(self, staging=False):
206
self._staging = staging
208
lp_base_url = uris.STAGING_SERVICE_ROOT
210
lp_base_url = uris.LPNET_SERVICE_ROOT
211
self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
215
return lp_api.uris.web_root_for_service_root(
216
str(self.launchpad._root_uri))
219
return "Launchpad(staging=%s)" % self._staging
221
def hosts(self, branch):
222
# TODO(jelmer): staging vs non-staging?
223
return plausible_launchpad_url(branch.user_url)
226
def probe_from_url(cls, url, possible_transports=None):
227
if plausible_launchpad_url(url):
229
raise UnsupportedHoster(url)
231
def _get_lp_git_ref_from_branch(self, branch):
232
url, params = urlutils.split_segment_parameters(branch.user_url)
233
(scheme, user, password, host, port, path) = urlutils.parse_url(
235
repo_lp = self.launchpad.git_repositories.getByPath(
236
path=path.strip('/'))
238
ref_path = params['ref']
240
branch_name = params.get('branch', branch.name)
242
ref_path = 'refs/heads/%s' % branch_name
244
ref_path = repo_lp.default_branch
245
ref_lp = repo_lp.getRefByPath(path=ref_path)
246
return (repo_lp, ref_lp)
248
def _get_lp_bzr_branch_from_branch(self, branch):
249
return self.launchpad.branches.getByUrl(
250
url=urlutils.unescape(branch.user_url))
252
def _get_derived_git_path(self, base_path, owner, project):
253
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
255
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
256
if project.startswith('~'):
257
project = '/'.join(base_path.split('/')[1:])
258
# TODO(jelmer): Surely there is a better way of creating one of these
260
return "~%s/%s" % (owner, project)
262
def _publish_git(self, local_branch, base_path, name, owner, project=None,
263
revision_id=None, overwrite=False, allow_lossy=True,
265
to_path = self._get_derived_git_path(base_path, owner, project)
266
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
268
dir_to = controldir.ControlDir.open_from_transport(to_transport)
269
except errors.NotBranchError:
270
# Didn't find anything
275
br_to = local_branch.create_clone_on_transport(
276
to_transport, revision_id=revision_id, name=name,
277
tag_selector=tag_selector)
278
except errors.NoRoundtrippingSupport:
279
br_to = local_branch.create_clone_on_transport(
280
to_transport, revision_id=revision_id, name=name,
281
lossy=True, tag_selector=tag_selector)
284
dir_to = dir_to.push_branch(
285
local_branch, revision_id, overwrite=overwrite, name=name,
286
tag_selector=tag_selector)
287
except errors.NoRoundtrippingSupport:
290
dir_to = dir_to.push_branch(
291
local_branch, revision_id, overwrite=overwrite, name=name,
292
lossy=True, tag_selector=tag_selector)
293
br_to = dir_to.target_branch
295
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
297
def _get_derived_bzr_path(self, base_branch, name, owner, project):
299
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
300
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
301
# TODO(jelmer): Surely there is a better way of creating one of these
303
return "~%s/%s/%s" % (owner, project, name)
305
def get_push_url(self, branch):
306
(vcs, user, password, path, params) = self._split_url(branch.user_url)
308
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
309
return branch_lp.bzr_identity
311
return urlutils.join_segment_parameters(
312
"git+ssh://git.launchpad.net/" + path, params)
316
def _publish_bzr(self, local_branch, base_branch, name, owner,
317
project=None, revision_id=None, overwrite=False,
318
allow_lossy=True, tag_selector=None):
319
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
320
to_transport = get_transport("lp:" + to_path)
322
dir_to = controldir.ControlDir.open_from_transport(to_transport)
323
except errors.NotBranchError:
324
# Didn't find anything
328
br_to = local_branch.create_clone_on_transport(
329
to_transport, revision_id=revision_id, tag_selector=tag_selector)
331
br_to = dir_to.push_branch(
332
local_branch, revision_id, overwrite=overwrite,
333
tag_selector=tag_selector).target_branch
334
return br_to, ("https://code.launchpad.net/" + to_path)
336
def _split_url(self, url):
337
url, params = urlutils.split_segment_parameters(url)
338
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
339
path = path.strip('/')
340
if host.startswith('bazaar.'):
342
elif host.startswith('git.'):
345
raise ValueError("unknown host %s" % host)
346
return (vcs, user, password, path, params)
348
def publish_derived(self, local_branch, base_branch, name, project=None,
349
owner=None, revision_id=None, overwrite=False,
350
allow_lossy=True, tag_selector=None):
351
"""Publish a branch to the site, derived from base_branch.
353
:param base_branch: branch to derive the new branch from
354
:param new_branch: branch to publish
355
:param name: Name of the new branch on the remote host
356
:param project: Optional project name
357
:param owner: Optional owner
358
:return: resulting branch
361
owner = self.launchpad.me.name
362
(base_vcs, base_user, base_password, base_path,
363
base_params) = self._split_url(base_branch.user_url)
364
# TODO(jelmer): Prevent publishing to development focus
365
if base_vcs == 'bzr':
366
return self._publish_bzr(
367
local_branch, base_branch, name, project=project, owner=owner,
368
revision_id=revision_id, overwrite=overwrite,
369
allow_lossy=allow_lossy, tag_selector=tag_selector)
370
elif base_vcs == 'git':
371
return self._publish_git(
372
local_branch, base_path, name, project=project, owner=owner,
373
revision_id=revision_id, overwrite=overwrite,
374
allow_lossy=allow_lossy, tag_selector=tag_selector)
376
raise AssertionError('not a valid Launchpad URL')
378
def get_derived_branch(self, base_branch, name, project=None, owner=None):
380
owner = self.launchpad.me.name
381
(base_vcs, base_user, base_password, base_path,
382
base_params) = self._split_url(base_branch.user_url)
383
if base_vcs == 'bzr':
384
to_path = self._get_derived_bzr_path(
385
base_branch, name, owner, project)
386
return _mod_branch.Branch.open("lp:" + to_path)
387
elif base_vcs == 'git':
388
to_path = self._get_derived_git_path(
389
base_path.strip('/'), owner, project)
390
to_url = urlutils.join_segment_parameters(
391
"git+ssh://git.launchpad.net/" + to_path,
393
return _mod_branch.Branch.open(to_url)
395
raise AssertionError('not a valid Launchpad URL')
397
def iter_proposals(self, source_branch, target_branch, status='open'):
398
(base_vcs, base_user, base_password, base_path,
399
base_params) = self._split_url(target_branch.user_url)
400
statuses = status_to_lp_mp_statuses(status)
401
if base_vcs == 'bzr':
402
target_branch_lp = self.launchpad.branches.getByUrl(
403
url=target_branch.user_url)
404
source_branch_lp = self.launchpad.branches.getByUrl(
405
url=source_branch.user_url)
406
for mp in target_branch_lp.getMergeProposals(status=statuses):
407
if mp.source_branch_link != source_branch_lp.self_link:
409
yield LaunchpadMergeProposal(mp)
410
elif base_vcs == 'git':
411
(source_repo_lp, source_branch_lp) = (
412
self._get_lp_git_ref_from_branch(source_branch))
413
(target_repo_lp, target_branch_lp) = (
414
self._get_lp_git_ref_from_branch(target_branch))
415
for mp in target_branch_lp.getMergeProposals(status=statuses):
416
if (target_branch_lp.path != mp.target_git_path or
417
target_repo_lp != mp.target_git_repository or
418
source_branch_lp.path != mp.source_git_path or
419
source_repo_lp != mp.source_git_repository):
421
yield LaunchpadMergeProposal(mp)
423
raise AssertionError('not a valid Launchpad URL')
425
def get_proposer(self, source_branch, target_branch):
426
(base_vcs, base_user, base_password, base_path,
427
base_params) = self._split_url(target_branch.user_url)
428
if base_vcs == 'bzr':
429
return LaunchpadBazaarMergeProposalBuilder(
430
self, source_branch, target_branch)
431
elif base_vcs == 'git':
432
return LaunchpadGitMergeProposalBuilder(
433
self, source_branch, target_branch)
435
raise AssertionError('not a valid Launchpad URL')
438
def iter_instances(cls):
441
def iter_my_proposals(self, status='open'):
442
statuses = status_to_lp_mp_statuses(status)
443
for mp in self.launchpad.me.getMergeProposals(status=statuses):
444
yield LaunchpadMergeProposal(mp)
446
def iter_my_forks(self):
447
# Launchpad doesn't really have the concept of "forks"
450
def get_proposal_by_url(self, url):
451
# Launchpad doesn't have a way to find a merge proposal by URL.
452
(scheme, user, password, host, port, path) = urlutils.parse_url(
454
LAUNCHPAD_CODE_DOMAINS = [
455
('code.%s' % domain) for domain in lp_uris.LAUNCHPAD_DOMAINS.values()]
456
if host not in LAUNCHPAD_CODE_DOMAINS:
457
raise UnsupportedHoster(url)
458
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
460
# See https://api.launchpad.net/devel/#branch_merge_proposal
462
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
463
api_url = str(self.launchpad._root_uri) + path
464
mp = self.launchpad.load(api_url)
465
return LaunchpadMergeProposal(mp)
468
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
470
def __init__(self, lp_host, source_branch, target_branch,
471
staging=None, approve=None, fixes=None):
474
:param source_branch: The branch to propose for merging.
475
:param target_branch: The branch to merge into.
476
:param staging: If True, propose the merge against staging instead of
478
:param approve: If True, mark the new proposal as approved immediately.
479
This is useful when a project permits some things to be approved
480
by the submitter (e.g. merges between release and deployment
483
self.lp_host = lp_host
484
self.launchpad = lp_host.launchpad
485
self.source_branch = source_branch
486
self.source_branch_lp = self.launchpad.branches.getByUrl(
487
url=source_branch.user_url)
488
if target_branch is None:
489
self.target_branch_lp = self.source_branch_lp.get_target()
490
self.target_branch = _mod_branch.Branch.open(
491
self.target_branch_lp.bzr_identity)
493
self.target_branch = target_branch
494
self.target_branch_lp = self.launchpad.branches.getByUrl(
495
url=target_branch.user_url)
496
self.approve = approve
499
def get_infotext(self):
500
"""Determine the initial comment for the merge proposal."""
501
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
502
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
505
def get_initial_body(self):
506
"""Get a body for the proposal for the user to modify.
508
:return: a str or None.
510
if not self.hooks['merge_proposal_body']:
513
def list_modified_files():
514
lca_tree = self.source_branch_lp.find_lca_tree(
515
self.target_branch_lp)
516
source_tree = self.source_branch.basis_tree()
517
files = modified_files(lca_tree, source_tree)
519
with self.target_branch.lock_read(), \
520
self.source_branch.lock_read():
522
for hook in self.hooks['merge_proposal_body']:
524
'target_branch': self.target_branch_lp.bzr_identity,
525
'modified_files_callback': list_modified_files,
530
def check_proposal(self):
531
"""Check that the submission is sensible."""
532
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
533
raise errors.BzrCommandError(
534
'Source and target branches must be different.')
535
for mp in self.source_branch_lp.landing_targets:
536
if mp.queue_status in ('Merged', 'Rejected'):
538
if mp.target_branch.self_link == self.target_branch_lp.self_link:
539
raise MergeProposalExists(lp_api.canonical_url(mp))
541
def approve_proposal(self, mp):
542
with self.source_branch.lock_read():
546
subject='', # Use the default subject.
547
content=u"Rubberstamp! Proposer approves of own proposal.")
548
_call_webservice(mp.setStatus, status=u'Approved',
549
revid=self.source_branch.last_revision())
551
def create_proposal(self, description, reviewers=None, labels=None,
552
prerequisite_branch=None, commit_message=None,
553
work_in_progress=False, allow_collaboration=False):
554
"""Perform the submission."""
556
raise LabelsUnsupported(self)
557
if prerequisite_branch is not None:
558
prereq = self.launchpad.branches.getByUrl(
559
url=prerequisite_branch.user_url)
562
if reviewers is None:
566
for reviewer in reviewers:
568
reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
570
reviewer_obj = self.launchpad.people[reviewer]
571
reviewer_objs.append(reviewer_obj)
573
mp = _call_webservice(
574
self.source_branch_lp.createMergeProposal,
575
target_branch=self.target_branch_lp,
576
prerequisite_branch=prereq,
577
initial_comment=description.strip(),
578
commit_message=commit_message,
579
needs_review=(not work_in_progress),
580
reviewers=[reviewer.self_link for reviewer in reviewer_objs],
581
review_types=['' for reviewer in reviewer_objs])
582
except WebserviceFailure as e:
584
if (b'There is already a branch merge proposal '
585
b'registered for branch ') in e.message:
586
raise MergeProposalExists(self.source_branch.user_url)
590
self.approve_proposal(mp)
592
if self.fixes.startswith('lp:'):
593
self.fixes = self.fixes[3:]
596
bug=self.launchpad.bugs[int(self.fixes)])
597
return LaunchpadMergeProposal(mp)
600
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
602
def __init__(self, lp_host, source_branch, target_branch,
603
staging=None, approve=None, fixes=None):
606
:param source_branch: The branch to propose for merging.
607
:param target_branch: The branch to merge into.
608
:param staging: If True, propose the merge against staging instead of
610
:param approve: If True, mark the new proposal as approved immediately.
611
This is useful when a project permits some things to be approved
612
by the submitter (e.g. merges between release and deployment
615
self.lp_host = lp_host
616
self.launchpad = lp_host.launchpad
617
self.source_branch = source_branch
618
(self.source_repo_lp,
619
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
621
if target_branch is None:
622
self.target_branch_lp = self.source_branch.get_target()
623
self.target_branch = _mod_branch.Branch.open(
624
self.target_branch_lp.git_https_url)
626
self.target_branch = target_branch
627
(self.target_repo_lp, self.target_branch_lp) = (
628
self.lp_host._get_lp_git_ref_from_branch(target_branch))
629
self.approve = approve
632
def get_infotext(self):
633
"""Determine the initial comment for the merge proposal."""
634
info = ["Source: %s\n" % self.source_branch.user_url]
635
info.append("Target: %s\n" % self.target_branch.user_url)
638
def get_initial_body(self):
639
"""Get a body for the proposal for the user to modify.
641
:return: a str or None.
643
if not self.hooks['merge_proposal_body']:
646
def list_modified_files():
647
lca_tree = self.source_branch_lp.find_lca_tree(
648
self.target_branch_lp)
649
source_tree = self.source_branch.basis_tree()
650
files = modified_files(lca_tree, source_tree)
652
with self.target_branch.lock_read(), \
653
self.source_branch.lock_read():
655
for hook in self.hooks['merge_proposal_body']:
657
'target_branch': self.target_branch,
658
'modified_files_callback': list_modified_files,
663
def check_proposal(self):
664
"""Check that the submission is sensible."""
665
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
666
raise errors.BzrCommandError(
667
'Source and target branches must be different.')
668
for mp in self.source_branch_lp.landing_targets:
669
if mp.queue_status in ('Merged', 'Rejected'):
671
if mp.target_branch.self_link == self.target_branch_lp.self_link:
672
raise MergeProposalExists(lp_api.canonical_url(mp))
674
def approve_proposal(self, mp):
675
with self.source_branch.lock_read():
679
subject='', # Use the default subject.
680
content=u"Rubberstamp! Proposer approves of own proposal.")
682
mp.setStatus, status=u'Approved',
683
revid=self.source_branch.last_revision())
685
def create_proposal(self, description, reviewers=None, labels=None,
686
prerequisite_branch=None, commit_message=None):
687
"""Perform the submission."""
689
raise LabelsUnsupported(self)
690
if prerequisite_branch is not None:
691
(prereq_repo_lp, prereq_branch_lp) = (
692
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
694
prereq_branch_lp = None
695
if reviewers is None:
698
mp = _call_webservice(
699
self.source_branch_lp.createMergeProposal,
700
merge_target=self.target_branch_lp,
701
merge_prerequisite=prereq_branch_lp,
702
initial_comment=description.strip(),
703
commit_message=commit_message,
705
reviewers=[self.launchpad.people[reviewer].self_link
706
for reviewer in reviewers],
707
review_types=[None for reviewer in reviewers])
708
except WebserviceFailure as e:
710
if ('There is already a branch merge proposal '
711
'registered for branch ') in e.message:
712
raise MergeProposalExists(self.source_branch.user_url)
715
self.approve_proposal(mp)
717
if self.fixes.startswith('lp:'):
718
self.fixes = self.fixes[3:]
721
bug=self.launchpad.bugs[int(self.fixes)])
722
return LaunchpadMergeProposal(mp)
725
def modified_files(old_tree, new_tree):
726
"""Return a list of paths in the new tree with modified contents."""
727
for change in new_tree.iter_changes(old_tree):
728
if change.changed_content and change.kind[1] == 'file':