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 (
49
from launchpadlib import uris
51
from ...transport import get_transport
54
# TODO(jelmer): Make selection of launchpad staging a configuration option.
56
def status_to_lp_mp_statuses(status):
58
if status in ('open', 'all'):
63
'Code failed to merge',
65
if status in ('closed', 'all'):
66
statuses.extend(['Rejected', 'Superseded'])
67
if status in ('merged', 'all'):
68
statuses.append('Merged')
72
def plausible_launchpad_url(url):
75
if url.startswith('lp:'):
77
regex = re.compile(r'([a-z]*\+)*(bzr\+ssh|http|ssh|git|https)'
78
r'://(bazaar|git).*\.launchpad\.net')
79
return bool(regex.match(url))
82
class WebserviceFailure(Exception):
84
def __init__(self, message):
85
self.message = message
88
def _call_webservice(call, *args, **kwargs):
89
"""Make a call to the webservice, wrapping failures.
91
:param call: The call to make.
92
:param *args: *args for the call.
93
:param **kwargs: **kwargs for the call.
94
:return: The result of calling call(*args, *kwargs).
96
from lazr.restfulclient import errors as restful_errors
98
return call(*args, **kwargs)
99
except restful_errors.HTTPError as e:
101
for line in e.content.splitlines():
102
if line.startswith(b'Traceback (most recent call last):'):
104
error_lines.append(line)
105
raise WebserviceFailure(b''.join(error_lines))
108
class LaunchpadMergeProposal(MergeProposal):
110
def __init__(self, mp):
113
def get_source_branch_url(self):
114
if self._mp.source_branch:
115
return self._mp.source_branch.bzr_identity
117
return git_url_to_bzr_url(
118
self._mp.source_git_repository.git_identity,
119
ref=self._mp.source_git_path.encode('utf-8'))
121
def get_target_branch_url(self):
122
if self._mp.target_branch:
123
return self._mp.target_branch.bzr_identity
125
return git_url_to_bzr_url(
126
self._mp.target_git_repository.git_identity,
127
ref=self._mp.target_git_path.encode('utf-8'))
131
return lp_api.canonical_url(self._mp)
134
return (self._mp.queue_status == 'Merged')
137
return (self._mp.queue_status in ('Rejected', 'Superseded'))
140
self._mp.setStatus(status='Needs review')
142
def get_description(self):
143
return self._mp.description
145
def set_description(self, description):
146
self._mp.description = description
149
def get_commit_message(self):
150
return self._mp.commit_message
152
def set_commit_message(self, commit_message):
153
self._mp.commit_message = commit_message
157
self._mp.setStatus(status='Rejected')
159
def can_be_merged(self):
160
if not self._mp.preview_diff:
163
return not bool(self._mp.preview_diff.conflicts)
165
def merge(self, commit_message=None):
166
target_branch = _mod_branch.Branch.open(
167
self.get_target_branch_url())
168
source_branch = _mod_branch.Branch.open(
169
self.get_source_branch_url())
170
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
172
# tree = target_branch.create_memorytree()
173
tmpdir = tempfile.mkdtemp()
175
tree = target_branch.create_checkout(
176
to_location=tmpdir, lightweight=True)
177
tree.merge_from_branch(source_branch)
178
tree.commit(commit_message or self._mp.commit_message)
180
shutil.rmtree(tmpdir)
183
class Launchpad(Hoster):
184
"""The Launchpad hosting service."""
188
# https://bugs.launchpad.net/launchpad/+bug/397676
189
supports_merge_proposal_labels = False
191
supports_merge_proposal_commit_message = True
193
def __init__(self, staging=False):
194
self._staging = staging
196
lp_base_url = uris.STAGING_SERVICE_ROOT
198
lp_base_url = uris.LPNET_SERVICE_ROOT
199
self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
203
return lp_api.uris.web_root_for_service_root(
204
str(self.launchpad._root_uri))
207
return "Launchpad(staging=%s)" % self._staging
209
def hosts(self, branch):
210
# TODO(jelmer): staging vs non-staging?
211
return plausible_launchpad_url(branch.user_url)
214
def probe_from_url(cls, url, possible_transports=None):
215
if plausible_launchpad_url(url):
217
raise UnsupportedHoster(url)
219
def _get_lp_git_ref_from_branch(self, branch):
220
url, params = urlutils.split_segment_parameters(branch.user_url)
221
(scheme, user, password, host, port, path) = urlutils.parse_url(
223
repo_lp = self.launchpad.git_repositories.getByPath(
224
path=path.strip('/'))
226
ref_path = params['ref']
228
branch_name = params.get('branch', branch.name)
230
ref_path = 'refs/heads/%s' % branch_name
232
ref_path = repo_lp.default_branch
233
ref_lp = repo_lp.getRefByPath(path=ref_path)
234
return (repo_lp, ref_lp)
236
def _get_lp_bzr_branch_from_branch(self, branch):
237
return self.launchpad.branches.getByUrl(
238
url=urlutils.unescape(branch.user_url))
240
def _get_derived_git_path(self, base_path, owner, project):
241
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
243
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
244
if project.startswith('~'):
245
project = '/'.join(base_path.split('/')[1:])
246
# TODO(jelmer): Surely there is a better way of creating one of these
248
return "~%s/%s" % (owner, project)
250
def _publish_git(self, local_branch, base_path, name, owner, project=None,
251
revision_id=None, overwrite=False, allow_lossy=True):
252
to_path = self._get_derived_git_path(base_path, owner, project)
253
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
255
dir_to = controldir.ControlDir.open_from_transport(to_transport)
256
except errors.NotBranchError:
257
# Didn't find anything
262
br_to = local_branch.create_clone_on_transport(
263
to_transport, revision_id=revision_id, name=name)
264
except errors.NoRoundtrippingSupport:
265
br_to = local_branch.create_clone_on_transport(
266
to_transport, revision_id=revision_id, name=name,
270
dir_to = dir_to.push_branch(
271
local_branch, revision_id, overwrite=overwrite, name=name)
272
except errors.NoRoundtrippingSupport:
275
dir_to = dir_to.push_branch(
276
local_branch, revision_id, overwrite=overwrite, name=name,
278
br_to = dir_to.target_branch
280
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
282
def _get_derived_bzr_path(self, base_branch, name, owner, project):
284
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
285
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
286
# TODO(jelmer): Surely there is a better way of creating one of these
288
return "~%s/%s/%s" % (owner, project, name)
290
def get_push_url(self, branch):
291
(vcs, user, password, path, params) = self._split_url(branch.user_url)
293
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
294
return branch_lp.bzr_identity
296
return urlutils.join_segment_parameters(
297
"git+ssh://git.launchpad.net/" + path, params)
301
def _publish_bzr(self, local_branch, base_branch, name, owner,
302
project=None, revision_id=None, overwrite=False,
304
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
305
to_transport = get_transport("lp:" + to_path)
307
dir_to = controldir.ControlDir.open_from_transport(to_transport)
308
except errors.NotBranchError:
309
# Didn't find anything
313
br_to = local_branch.create_clone_on_transport(
314
to_transport, revision_id=revision_id)
316
br_to = dir_to.push_branch(
317
local_branch, revision_id, overwrite=overwrite).target_branch
318
return br_to, ("https://code.launchpad.net/" + to_path)
320
def _split_url(self, url):
321
url, params = urlutils.split_segment_parameters(url)
322
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
323
path = path.strip('/')
324
if host.startswith('bazaar.'):
326
elif host.startswith('git.'):
329
raise ValueError("unknown host %s" % host)
330
return (vcs, user, password, path, params)
332
def publish_derived(self, local_branch, base_branch, name, project=None,
333
owner=None, revision_id=None, overwrite=False,
335
"""Publish a branch to the site, derived from base_branch.
337
:param base_branch: branch to derive the new branch from
338
:param new_branch: branch to publish
339
:param name: Name of the new branch on the remote host
340
:param project: Optional project name
341
:param owner: Optional owner
342
:return: resulting branch
345
owner = self.launchpad.me.name
346
(base_vcs, base_user, base_password, base_path,
347
base_params) = self._split_url(base_branch.user_url)
348
# TODO(jelmer): Prevent publishing to development focus
349
if base_vcs == 'bzr':
350
return self._publish_bzr(
351
local_branch, base_branch, name, project=project, owner=owner,
352
revision_id=revision_id, overwrite=overwrite,
353
allow_lossy=allow_lossy)
354
elif base_vcs == 'git':
355
return self._publish_git(
356
local_branch, base_path, name, project=project, owner=owner,
357
revision_id=revision_id, overwrite=overwrite,
358
allow_lossy=allow_lossy)
360
raise AssertionError('not a valid Launchpad URL')
362
def get_derived_branch(self, base_branch, name, project=None, owner=None):
364
owner = self.launchpad.me.name
365
(base_vcs, base_user, base_password, base_path,
366
base_params) = self._split_url(base_branch.user_url)
367
if base_vcs == 'bzr':
368
to_path = self._get_derived_bzr_path(
369
base_branch, name, owner, project)
370
return _mod_branch.Branch.open("lp:" + to_path)
371
elif base_vcs == 'git':
372
to_path = self._get_derived_git_path(
373
base_path.strip('/'), owner, project)
374
to_url = urlutils.join_segment_parameters(
375
"git+ssh://git.launchpad.net/" + to_path,
377
return _mod_branch.Branch.open(to_url)
379
raise AssertionError('not a valid Launchpad URL')
381
def iter_proposals(self, source_branch, target_branch, status='open'):
382
(base_vcs, base_user, base_password, base_path,
383
base_params) = self._split_url(target_branch.user_url)
384
statuses = status_to_lp_mp_statuses(status)
385
if base_vcs == 'bzr':
386
target_branch_lp = self.launchpad.branches.getByUrl(
387
url=target_branch.user_url)
388
source_branch_lp = self.launchpad.branches.getByUrl(
389
url=source_branch.user_url)
390
for mp in target_branch_lp.getMergeProposals(status=statuses):
391
if mp.source_branch_link != source_branch_lp.self_link:
393
yield LaunchpadMergeProposal(mp)
394
elif base_vcs == 'git':
395
(source_repo_lp, source_branch_lp) = (
396
self._get_lp_git_ref_from_branch(source_branch))
397
(target_repo_lp, target_branch_lp) = (
398
self._get_lp_git_ref_from_branch(target_branch))
399
for mp in target_branch_lp.getMergeProposals(status=statuses):
400
if (target_branch_lp.path != mp.target_git_path or
401
target_repo_lp != mp.target_git_repository or
402
source_branch_lp.path != mp.source_git_path or
403
source_repo_lp != mp.source_git_repository):
405
yield LaunchpadMergeProposal(mp)
407
raise AssertionError('not a valid Launchpad URL')
409
def get_proposer(self, source_branch, target_branch):
410
(base_vcs, base_user, base_password, base_path,
411
base_params) = self._split_url(target_branch.user_url)
412
if base_vcs == 'bzr':
413
return LaunchpadBazaarMergeProposalBuilder(
414
self, source_branch, target_branch)
415
elif base_vcs == 'git':
416
return LaunchpadGitMergeProposalBuilder(
417
self, source_branch, target_branch)
419
raise AssertionError('not a valid Launchpad URL')
422
def iter_instances(cls):
425
def iter_my_proposals(self, status='open'):
426
statuses = status_to_lp_mp_statuses(status)
427
for mp in self.launchpad.me.getMergeProposals(status=statuses):
428
yield LaunchpadMergeProposal(mp)
430
def get_proposal_by_url(self, url):
431
# Launchpad doesn't have a way to find a merge proposal by URL.
432
(scheme, user, password, host, port, path) = urlutils.parse_url(
434
LAUNCHPAD_CODE_DOMAINS = [
435
('code.%s' % domain) for domain in lp_api.LAUNCHPAD_DOMAINS.values()]
436
if host not in LAUNCHPAD_CODE_DOMAINS:
437
raise UnsupportedHoster(url)
438
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
440
# See https://api.launchpad.net/devel/#branch_merge_proposal
442
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
443
api_url = str(self.launchpad._root_uri) + path
444
mp = self.launchpad.load(api_url)
445
return LaunchpadMergeProposal(mp)
448
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
450
def __init__(self, lp_host, source_branch, target_branch,
451
staging=None, approve=None, fixes=None):
454
:param source_branch: The branch to propose for merging.
455
:param target_branch: The branch to merge into.
456
:param staging: If True, propose the merge against staging instead of
458
:param approve: If True, mark the new proposal as approved immediately.
459
This is useful when a project permits some things to be approved
460
by the submitter (e.g. merges between release and deployment
463
self.lp_host = lp_host
464
self.launchpad = lp_host.launchpad
465
self.source_branch = source_branch
466
self.source_branch_lp = self.launchpad.branches.getByUrl(
467
url=source_branch.user_url)
468
if target_branch is None:
469
self.target_branch_lp = self.source_branch_lp.get_target()
470
self.target_branch = _mod_branch.Branch.open(
471
self.target_branch_lp.bzr_identity)
473
self.target_branch = target_branch
474
self.target_branch_lp = self.launchpad.branches.getByUrl(
475
url=target_branch.user_url)
476
self.approve = approve
479
def get_infotext(self):
480
"""Determine the initial comment for the merge proposal."""
481
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
482
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
485
def get_initial_body(self):
486
"""Get a body for the proposal for the user to modify.
488
:return: a str or None.
490
if not self.hooks['merge_proposal_body']:
493
def list_modified_files():
494
lca_tree = self.source_branch_lp.find_lca_tree(
495
self.target_branch_lp)
496
source_tree = self.source_branch.basis_tree()
497
files = modified_files(lca_tree, source_tree)
499
with self.target_branch.lock_read(), \
500
self.source_branch.lock_read():
502
for hook in self.hooks['merge_proposal_body']:
504
'target_branch': self.target_branch_lp.bzr_identity,
505
'modified_files_callback': list_modified_files,
510
def check_proposal(self):
511
"""Check that the submission is sensible."""
512
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
513
raise errors.BzrCommandError(
514
'Source and target branches must be different.')
515
for mp in self.source_branch_lp.landing_targets:
516
if mp.queue_status in ('Merged', 'Rejected'):
518
if mp.target_branch.self_link == self.target_branch_lp.self_link:
519
raise MergeProposalExists(lp_api.canonical_url(mp))
521
def approve_proposal(self, mp):
522
with self.source_branch.lock_read():
526
subject='', # Use the default subject.
527
content=u"Rubberstamp! Proposer approves of own proposal.")
528
_call_webservice(mp.setStatus, status=u'Approved',
529
revid=self.source_branch.last_revision())
531
def create_proposal(self, description, reviewers=None, labels=None,
532
prerequisite_branch=None, commit_message=None):
533
"""Perform the submission."""
535
raise LabelsUnsupported(self)
536
if prerequisite_branch is not None:
537
prereq = self.launchpad.branches.getByUrl(
538
url=prerequisite_branch.user_url)
541
if reviewers is None:
545
for reviewer in reviewers:
547
reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
549
reviewer_obj = self.launchpad.people[reviewer]
550
reviewer_objs.append(reviewer_obj)
552
mp = _call_webservice(
553
self.source_branch_lp.createMergeProposal,
554
target_branch=self.target_branch_lp,
555
prerequisite_branch=prereq,
556
initial_comment=description.strip(),
557
commit_message=commit_message,
558
reviewers=[reviewer.self_link for reviewer in reviewer_objs],
559
review_types=['' for reviewer in reviewer_objs])
560
except WebserviceFailure as e:
562
if (b'There is already a branch merge proposal '
563
b'registered for branch ') in e.message:
564
raise MergeProposalExists(self.source_branch.user_url)
568
self.approve_proposal(mp)
570
if self.fixes.startswith('lp:'):
571
self.fixes = self.fixes[3:]
574
bug=self.launchpad.bugs[int(self.fixes)])
575
return LaunchpadMergeProposal(mp)
578
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
580
def __init__(self, lp_host, source_branch, target_branch,
581
staging=None, approve=None, fixes=None):
584
:param source_branch: The branch to propose for merging.
585
:param target_branch: The branch to merge into.
586
:param staging: If True, propose the merge against staging instead of
588
:param approve: If True, mark the new proposal as approved immediately.
589
This is useful when a project permits some things to be approved
590
by the submitter (e.g. merges between release and deployment
593
self.lp_host = lp_host
594
self.launchpad = lp_host.launchpad
595
self.source_branch = source_branch
596
(self.source_repo_lp,
597
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
599
if target_branch is None:
600
self.target_branch_lp = self.source_branch.get_target()
601
self.target_branch = _mod_branch.Branch.open(
602
self.target_branch_lp.git_https_url)
604
self.target_branch = target_branch
605
(self.target_repo_lp, self.target_branch_lp) = (
606
self.lp_host._get_lp_git_ref_from_branch(target_branch))
607
self.approve = approve
610
def get_infotext(self):
611
"""Determine the initial comment for the merge proposal."""
612
info = ["Source: %s\n" % self.source_branch.user_url]
613
info.append("Target: %s\n" % self.target_branch.user_url)
616
def get_initial_body(self):
617
"""Get a body for the proposal for the user to modify.
619
:return: a str or None.
621
if not self.hooks['merge_proposal_body']:
624
def list_modified_files():
625
lca_tree = self.source_branch_lp.find_lca_tree(
626
self.target_branch_lp)
627
source_tree = self.source_branch.basis_tree()
628
files = modified_files(lca_tree, source_tree)
630
with self.target_branch.lock_read(), \
631
self.source_branch.lock_read():
633
for hook in self.hooks['merge_proposal_body']:
635
'target_branch': self.target_branch,
636
'modified_files_callback': list_modified_files,
641
def check_proposal(self):
642
"""Check that the submission is sensible."""
643
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
644
raise errors.BzrCommandError(
645
'Source and target branches must be different.')
646
for mp in self.source_branch_lp.landing_targets:
647
if mp.queue_status in ('Merged', 'Rejected'):
649
if mp.target_branch.self_link == self.target_branch_lp.self_link:
650
raise MergeProposalExists(lp_api.canonical_url(mp))
652
def approve_proposal(self, mp):
653
with self.source_branch.lock_read():
657
subject='', # Use the default subject.
658
content=u"Rubberstamp! Proposer approves of own proposal.")
660
mp.setStatus, status=u'Approved',
661
revid=self.source_branch.last_revision())
663
def create_proposal(self, description, reviewers=None, labels=None,
664
prerequisite_branch=None, commit_message=None):
665
"""Perform the submission."""
667
raise LabelsUnsupported(self)
668
if prerequisite_branch is not None:
669
(prereq_repo_lp, prereq_branch_lp) = (
670
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
672
prereq_branch_lp = None
673
if reviewers is None:
676
mp = _call_webservice(
677
self.source_branch_lp.createMergeProposal,
678
merge_target=self.target_branch_lp,
679
merge_prerequisite=prereq_branch_lp,
680
initial_comment=description.strip(),
681
commit_message=commit_message,
683
reviewers=[self.launchpad.people[reviewer].self_link
684
for reviewer in reviewers],
685
review_types=[None for reviewer in reviewers])
686
except WebserviceFailure as e:
688
if ('There is already a branch merge proposal '
689
'registered for branch ') in e.message:
690
raise MergeProposalExists(self.source_branch.user_url)
693
self.approve_proposal(mp)
695
if self.fixes.startswith('lp:'):
696
self.fixes = self.fixes[3:]
699
bug=self.launchpad.bugs[int(self.fixes)])
700
return LaunchpadMergeProposal(mp)
703
def modified_files(old_tree, new_tree):
704
"""Return a list of paths in the new tree with modified contents."""
705
for change in new_tree.iter_changes(old_tree):
706
if change.changed_content and change.kind[1] == 'file':