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_source_revision(self):
123
if self._mp.source_branch:
124
last_scanned_id = self._mp.source_branch.last_scanned_id
126
return last_scanned_id.encode('utf-8')
130
from breezy.git.mapping import default_mapping
131
git_repo = self._mp.source_git_repository
132
git_ref = git_repo.getRefByPath(path=self._mp.source_git_path)
133
sha = git_ref.commit_sha1
136
return default_mapping.revision_id_foreign_to_bzr(
139
def get_target_branch_url(self):
140
if self._mp.target_branch:
141
return self._mp.target_branch.bzr_identity
143
return git_url_to_bzr_url(
144
self._mp.target_git_repository.git_identity,
145
ref=self._mp.target_git_path.encode('utf-8'))
149
return lp_api.canonical_url(self._mp)
152
return (self._mp.queue_status == 'Merged')
155
return (self._mp.queue_status in ('Rejected', 'Superseded'))
158
self._mp.setStatus(status='Needs review')
160
def get_description(self):
161
return self._mp.description
163
def set_description(self, description):
164
self._mp.description = description
167
def get_commit_message(self):
168
return self._mp.commit_message
170
def set_commit_message(self, commit_message):
171
self._mp.commit_message = commit_message
175
self._mp.setStatus(status='Rejected')
177
def can_be_merged(self):
178
if not self._mp.preview_diff:
181
return not bool(self._mp.preview_diff.conflicts)
183
def get_merged_by(self):
184
merge_reporter = self._mp.merge_reporter
185
if merge_reporter is None:
187
return merge_reporter.name
189
def get_merged_at(self):
190
return self._mp.date_merged
192
def merge(self, commit_message=None):
193
target_branch = _mod_branch.Branch.open(
194
self.get_target_branch_url())
195
source_branch = _mod_branch.Branch.open(
196
self.get_source_branch_url())
197
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
199
# tree = target_branch.create_memorytree()
200
tmpdir = tempfile.mkdtemp()
202
tree = target_branch.create_checkout(
203
to_location=tmpdir, lightweight=True)
204
tree.merge_from_branch(source_branch)
205
tree.commit(commit_message or self._mp.commit_message)
207
shutil.rmtree(tmpdir)
209
def post_comment(self, body):
210
self._mp.createComment(content=body)
213
class Launchpad(Hoster):
214
"""The Launchpad hosting service."""
218
# https://bugs.launchpad.net/launchpad/+bug/397676
219
supports_merge_proposal_labels = False
221
supports_merge_proposal_commit_message = True
223
supports_allow_collaboration = False
225
merge_proposal_description_format = 'plain'
227
def __init__(self, staging=False):
228
self._staging = staging
230
lp_base_url = uris.STAGING_SERVICE_ROOT
232
lp_base_url = uris.LPNET_SERVICE_ROOT
233
self._api_base_url = lp_base_url
234
self._launchpad = None
238
if self._launchpad is None:
239
self._launchpad = lp_api.connect_launchpad(self._api_base_url, version='devel')
240
return self._launchpad
244
return lp_api.uris.web_root_for_service_root(self._api_base_url)
247
return "Launchpad(staging=%s)" % self._staging
249
def hosts(self, branch):
250
# TODO(jelmer): staging vs non-staging?
251
return plausible_launchpad_url(branch.user_url)
254
def probe_from_url(cls, url, possible_transports=None):
255
if plausible_launchpad_url(url):
257
raise UnsupportedHoster(url)
259
def _get_lp_git_ref_from_branch(self, branch):
260
url, params = urlutils.split_segment_parameters(branch.user_url)
261
(scheme, user, password, host, port, path) = urlutils.parse_url(
263
repo_lp = self.launchpad.git_repositories.getByPath(
264
path=path.strip('/'))
266
ref_path = params['ref']
268
branch_name = params.get('branch', branch.name)
270
ref_path = 'refs/heads/%s' % branch_name
272
ref_path = repo_lp.default_branch
273
ref_lp = repo_lp.getRefByPath(path=ref_path)
274
return (repo_lp, ref_lp)
276
def _get_lp_bzr_branch_from_branch(self, branch):
277
return self.launchpad.branches.getByUrl(
278
url=urlutils.unescape(branch.user_url))
280
def _get_derived_git_path(self, base_path, owner, project):
281
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
283
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
284
if project.startswith('~'):
285
project = '/'.join(base_path.split('/')[1:])
286
# TODO(jelmer): Surely there is a better way of creating one of these
288
return "~%s/%s" % (owner, project)
290
def _publish_git(self, local_branch, base_path, name, owner, project=None,
291
revision_id=None, overwrite=False, allow_lossy=True,
293
to_path = self._get_derived_git_path(base_path, owner, project)
294
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
296
dir_to = controldir.ControlDir.open_from_transport(to_transport)
297
except errors.NotBranchError:
298
# Didn't find anything
303
br_to = local_branch.create_clone_on_transport(
304
to_transport, revision_id=revision_id, name=name,
305
tag_selector=tag_selector)
306
except errors.NoRoundtrippingSupport:
307
br_to = local_branch.create_clone_on_transport(
308
to_transport, revision_id=revision_id, name=name,
309
lossy=True, tag_selector=tag_selector)
312
dir_to = dir_to.push_branch(
313
local_branch, revision_id, overwrite=overwrite, name=name,
314
tag_selector=tag_selector)
315
except errors.NoRoundtrippingSupport:
318
dir_to = dir_to.push_branch(
319
local_branch, revision_id, overwrite=overwrite, name=name,
320
lossy=True, tag_selector=tag_selector)
321
br_to = dir_to.target_branch
323
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
325
def _get_derived_bzr_path(self, base_branch, name, owner, project):
327
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
328
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
329
# TODO(jelmer): Surely there is a better way of creating one of these
331
return "~%s/%s/%s" % (owner, project, name)
333
def get_push_url(self, branch):
334
(vcs, user, password, path, params) = self._split_url(branch.user_url)
336
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
337
return branch_lp.bzr_identity
339
return urlutils.join_segment_parameters(
340
"git+ssh://git.launchpad.net/" + path, params)
344
def _publish_bzr(self, local_branch, base_branch, name, owner,
345
project=None, revision_id=None, overwrite=False,
346
allow_lossy=True, tag_selector=None):
347
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
348
to_transport = get_transport("lp:" + to_path)
350
dir_to = controldir.ControlDir.open_from_transport(to_transport)
351
except errors.NotBranchError:
352
# Didn't find anything
356
br_to = local_branch.create_clone_on_transport(
357
to_transport, revision_id=revision_id, tag_selector=tag_selector)
359
br_to = dir_to.push_branch(
360
local_branch, revision_id, overwrite=overwrite,
361
tag_selector=tag_selector).target_branch
362
return br_to, ("https://code.launchpad.net/" + to_path)
364
def _split_url(self, url):
365
url, params = urlutils.split_segment_parameters(url)
366
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
367
path = path.strip('/')
368
if host.startswith('bazaar.'):
370
elif host.startswith('git.'):
373
raise ValueError("unknown host %s" % host)
374
return (vcs, user, password, path, params)
376
def publish_derived(self, local_branch, base_branch, name, project=None,
377
owner=None, revision_id=None, overwrite=False,
378
allow_lossy=True, tag_selector=None):
379
"""Publish a branch to the site, derived from base_branch.
381
:param base_branch: branch to derive the new branch from
382
:param new_branch: branch to publish
383
:param name: Name of the new branch on the remote host
384
:param project: Optional project name
385
:param owner: Optional owner
386
:return: resulting branch
389
owner = self.launchpad.me.name
390
(base_vcs, base_user, base_password, base_path,
391
base_params) = self._split_url(base_branch.user_url)
392
# TODO(jelmer): Prevent publishing to development focus
393
if base_vcs == 'bzr':
394
return self._publish_bzr(
395
local_branch, base_branch, name, project=project, owner=owner,
396
revision_id=revision_id, overwrite=overwrite,
397
allow_lossy=allow_lossy, tag_selector=tag_selector)
398
elif base_vcs == 'git':
399
return self._publish_git(
400
local_branch, base_path, name, project=project, owner=owner,
401
revision_id=revision_id, overwrite=overwrite,
402
allow_lossy=allow_lossy, tag_selector=tag_selector)
404
raise AssertionError('not a valid Launchpad URL')
406
def get_derived_branch(self, base_branch, name, project=None, owner=None):
408
owner = self.launchpad.me.name
409
(base_vcs, base_user, base_password, base_path,
410
base_params) = self._split_url(base_branch.user_url)
411
if base_vcs == 'bzr':
412
to_path = self._get_derived_bzr_path(
413
base_branch, name, owner, project)
414
return _mod_branch.Branch.open("lp:" + to_path)
415
elif base_vcs == 'git':
416
to_path = self._get_derived_git_path(
417
base_path.strip('/'), owner, project)
418
to_url = urlutils.join_segment_parameters(
419
"git+ssh://git.launchpad.net/" + to_path,
421
return _mod_branch.Branch.open(to_url)
423
raise AssertionError('not a valid Launchpad URL')
425
def iter_proposals(self, source_branch, target_branch, status='open'):
426
(base_vcs, base_user, base_password, base_path,
427
base_params) = self._split_url(target_branch.user_url)
428
statuses = status_to_lp_mp_statuses(status)
429
if base_vcs == 'bzr':
430
target_branch_lp = self.launchpad.branches.getByUrl(
431
url=target_branch.user_url)
432
source_branch_lp = self.launchpad.branches.getByUrl(
433
url=source_branch.user_url)
434
for mp in target_branch_lp.getMergeProposals(status=statuses):
435
if mp.source_branch_link != source_branch_lp.self_link:
437
yield LaunchpadMergeProposal(mp)
438
elif base_vcs == 'git':
439
(source_repo_lp, source_branch_lp) = (
440
self._get_lp_git_ref_from_branch(source_branch))
441
(target_repo_lp, target_branch_lp) = (
442
self._get_lp_git_ref_from_branch(target_branch))
443
for mp in target_branch_lp.getMergeProposals(status=statuses):
444
if (target_branch_lp.path != mp.target_git_path or
445
target_repo_lp != mp.target_git_repository or
446
source_branch_lp.path != mp.source_git_path or
447
source_repo_lp != mp.source_git_repository):
449
yield LaunchpadMergeProposal(mp)
451
raise AssertionError('not a valid Launchpad URL')
453
def get_proposer(self, source_branch, target_branch):
454
(base_vcs, base_user, base_password, base_path,
455
base_params) = self._split_url(target_branch.user_url)
456
if base_vcs == 'bzr':
457
return LaunchpadBazaarMergeProposalBuilder(
458
self, source_branch, target_branch)
459
elif base_vcs == 'git':
460
return LaunchpadGitMergeProposalBuilder(
461
self, source_branch, target_branch)
463
raise AssertionError('not a valid Launchpad URL')
466
def iter_instances(cls):
469
def iter_my_proposals(self, status='open'):
470
statuses = status_to_lp_mp_statuses(status)
471
for mp in self.launchpad.me.getMergeProposals(status=statuses):
472
yield LaunchpadMergeProposal(mp)
474
def iter_my_forks(self):
475
# Launchpad doesn't really have the concept of "forks"
478
def get_proposal_by_url(self, url):
479
# Launchpad doesn't have a way to find a merge proposal by URL.
480
(scheme, user, password, host, port, path) = urlutils.parse_url(
482
LAUNCHPAD_CODE_DOMAINS = [
483
('code.%s' % domain) for domain in lp_uris.LAUNCHPAD_DOMAINS.values()]
484
if host not in LAUNCHPAD_CODE_DOMAINS:
485
raise UnsupportedHoster(url)
486
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
488
# See https://api.launchpad.net/devel/#branch_merge_proposal
490
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
491
api_url = str(self.launchpad._root_uri) + path
492
mp = self.launchpad.load(api_url)
493
return LaunchpadMergeProposal(mp)
496
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
498
def __init__(self, lp_host, source_branch, target_branch,
499
staging=None, approve=None, fixes=None):
502
:param source_branch: The branch to propose for merging.
503
:param target_branch: The branch to merge into.
504
:param staging: If True, propose the merge against staging instead of
506
:param approve: If True, mark the new proposal as approved immediately.
507
This is useful when a project permits some things to be approved
508
by the submitter (e.g. merges between release and deployment
511
self.lp_host = lp_host
512
self.launchpad = lp_host.launchpad
513
self.source_branch = source_branch
514
self.source_branch_lp = self.launchpad.branches.getByUrl(
515
url=source_branch.user_url)
516
if target_branch is None:
517
self.target_branch_lp = self.source_branch_lp.get_target()
518
self.target_branch = _mod_branch.Branch.open(
519
self.target_branch_lp.bzr_identity)
521
self.target_branch = target_branch
522
self.target_branch_lp = self.launchpad.branches.getByUrl(
523
url=target_branch.user_url)
524
self.approve = approve
527
def get_infotext(self):
528
"""Determine the initial comment for the merge proposal."""
529
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
530
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
533
def get_initial_body(self):
534
"""Get a body for the proposal for the user to modify.
536
:return: a str or None.
538
if not self.hooks['merge_proposal_body']:
541
def list_modified_files():
542
lca_tree = self.source_branch_lp.find_lca_tree(
543
self.target_branch_lp)
544
source_tree = self.source_branch.basis_tree()
545
files = modified_files(lca_tree, source_tree)
547
with self.target_branch.lock_read(), \
548
self.source_branch.lock_read():
550
for hook in self.hooks['merge_proposal_body']:
552
'target_branch': self.target_branch_lp.bzr_identity,
553
'modified_files_callback': list_modified_files,
558
def check_proposal(self):
559
"""Check that the submission is sensible."""
560
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
561
raise errors.CommandError(
562
'Source and target branches must be different.')
563
for mp in self.source_branch_lp.landing_targets:
564
if mp.queue_status in ('Merged', 'Rejected'):
566
if mp.target_branch.self_link == self.target_branch_lp.self_link:
567
raise MergeProposalExists(lp_api.canonical_url(mp))
569
def approve_proposal(self, mp):
570
with self.source_branch.lock_read():
574
subject='', # Use the default subject.
575
content=u"Rubberstamp! Proposer approves of own proposal.")
576
_call_webservice(mp.setStatus, status=u'Approved',
577
revid=self.source_branch.last_revision())
579
def create_proposal(self, description, reviewers=None, labels=None,
580
prerequisite_branch=None, commit_message=None,
581
work_in_progress=False, allow_collaboration=False):
582
"""Perform the submission."""
584
raise LabelsUnsupported(self)
585
if prerequisite_branch is not None:
586
prereq = self.launchpad.branches.getByUrl(
587
url=prerequisite_branch.user_url)
590
if reviewers is None:
594
for reviewer in reviewers:
596
reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
598
reviewer_obj = self.launchpad.people[reviewer]
599
reviewer_objs.append(reviewer_obj)
601
mp = _call_webservice(
602
self.source_branch_lp.createMergeProposal,
603
target_branch=self.target_branch_lp,
604
prerequisite_branch=prereq,
605
initial_comment=description.strip(),
606
commit_message=commit_message,
607
needs_review=(not work_in_progress),
608
reviewers=[reviewer.self_link for reviewer in reviewer_objs],
609
review_types=['' for reviewer in reviewer_objs])
610
except WebserviceFailure as e:
612
if (b'There is already a branch merge proposal '
613
b'registered for branch ') in e.message:
614
raise MergeProposalExists(self.source_branch.user_url)
618
self.approve_proposal(mp)
620
if self.fixes.startswith('lp:'):
621
self.fixes = self.fixes[3:]
624
bug=self.launchpad.bugs[int(self.fixes)])
625
return LaunchpadMergeProposal(mp)
628
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
630
def __init__(self, lp_host, source_branch, target_branch,
631
staging=None, approve=None, fixes=None):
634
:param source_branch: The branch to propose for merging.
635
:param target_branch: The branch to merge into.
636
:param staging: If True, propose the merge against staging instead of
638
:param approve: If True, mark the new proposal as approved immediately.
639
This is useful when a project permits some things to be approved
640
by the submitter (e.g. merges between release and deployment
643
self.lp_host = lp_host
644
self.launchpad = lp_host.launchpad
645
self.source_branch = source_branch
646
(self.source_repo_lp,
647
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
649
if target_branch is None:
650
self.target_branch_lp = self.source_branch.get_target()
651
self.target_branch = _mod_branch.Branch.open(
652
self.target_branch_lp.git_https_url)
654
self.target_branch = target_branch
655
(self.target_repo_lp, self.target_branch_lp) = (
656
self.lp_host._get_lp_git_ref_from_branch(target_branch))
657
self.approve = approve
660
def get_infotext(self):
661
"""Determine the initial comment for the merge proposal."""
662
info = ["Source: %s\n" % self.source_branch.user_url]
663
info.append("Target: %s\n" % self.target_branch.user_url)
666
def get_initial_body(self):
667
"""Get a body for the proposal for the user to modify.
669
:return: a str or None.
671
if not self.hooks['merge_proposal_body']:
674
def list_modified_files():
675
lca_tree = self.source_branch_lp.find_lca_tree(
676
self.target_branch_lp)
677
source_tree = self.source_branch.basis_tree()
678
files = modified_files(lca_tree, source_tree)
680
with self.target_branch.lock_read(), \
681
self.source_branch.lock_read():
683
for hook in self.hooks['merge_proposal_body']:
685
'target_branch': self.target_branch,
686
'modified_files_callback': list_modified_files,
691
def check_proposal(self):
692
"""Check that the submission is sensible."""
693
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
694
raise errors.CommandError(
695
'Source and target branches must be different.')
696
for mp in self.source_branch_lp.landing_targets:
697
if mp.queue_status in ('Merged', 'Rejected'):
699
if mp.target_branch.self_link == self.target_branch_lp.self_link:
700
raise MergeProposalExists(lp_api.canonical_url(mp))
702
def approve_proposal(self, mp):
703
with self.source_branch.lock_read():
707
subject='', # Use the default subject.
708
content=u"Rubberstamp! Proposer approves of own proposal.")
710
mp.setStatus, status=u'Approved',
711
revid=self.source_branch.last_revision())
713
def create_proposal(self, description, reviewers=None, labels=None,
714
prerequisite_branch=None, commit_message=None):
715
"""Perform the submission."""
717
raise LabelsUnsupported(self)
718
if prerequisite_branch is not None:
719
(prereq_repo_lp, prereq_branch_lp) = (
720
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
722
prereq_branch_lp = None
723
if reviewers is None:
726
mp = _call_webservice(
727
self.source_branch_lp.createMergeProposal,
728
merge_target=self.target_branch_lp,
729
merge_prerequisite=prereq_branch_lp,
730
initial_comment=description.strip(),
731
commit_message=commit_message,
733
reviewers=[self.launchpad.people[reviewer].self_link
734
for reviewer in reviewers],
735
review_types=[None for reviewer in reviewers])
736
except WebserviceFailure as e:
738
if ('There is already a branch merge proposal '
739
'registered for branch ') in e.message:
740
raise MergeProposalExists(self.source_branch.user_url)
743
self.approve_proposal(mp)
745
if self.fixes.startswith('lp:'):
746
self.fixes = self.fixes[3:]
749
bug=self.launchpad.bugs[int(self.fixes)])
750
return LaunchpadMergeProposal(mp)
753
def modified_files(old_tree, new_tree):
754
"""Return a list of paths in the new tree with modified contents."""
755
for change in new_tree.iter_changes(old_tree):
756
if change.changed_content and change.kind[1] == 'file':