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.refs import ref_to_branch_name
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
branch_name = ref_to_branch_name(
118
self._mp.source_git_path.encode('utf-8'))
119
return urlutils.join_segment_parameters(
120
self._mp.source_git_repository.git_identity,
121
{"branch": str(branch_name)})
123
def get_target_branch_url(self):
124
if self._mp.target_branch:
125
return self._mp.target_branch.bzr_identity
127
branch_name = ref_to_branch_name(
128
self._mp.target_git_path.encode('utf-8'))
129
return urlutils.join_segment_parameters(
130
self._mp.target_git_repository.git_identity,
131
{"branch": str(branch_name)})
135
return lp_api.canonical_url(self._mp)
138
return (self._mp.queue_status == 'Merged')
140
def get_description(self):
141
return self._mp.description
143
def set_description(self, description):
144
self._mp.description = description
147
def get_commit_message(self):
148
return self._mp.commit_message
150
def set_commit_message(self, commit_message):
151
self._mp.commit_message = commit_message
155
self._mp.setStatus(status='Rejected')
157
def can_be_merged(self):
158
if not self._mp.preview_diff:
161
return not bool(self._mp.preview_diff.conflicts)
163
def merge(self, commit_message=None):
164
target_branch = _mod_branch.Branch.open(
165
self.get_target_branch_url())
166
source_branch = _mod_branch.Branch.open(
167
self.get_source_branch_url())
168
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
170
# tree = target_branch.create_memorytree()
171
tmpdir = tempfile.mkdtemp()
173
tree = target_branch.create_checkout(
174
to_location=tmpdir, lightweight=True)
175
tree.merge_from_branch(source_branch)
176
tree.commit(commit_message or self._mp.commit_message)
178
shutil.rmtree(tmpdir)
181
class Launchpad(Hoster):
182
"""The Launchpad hosting service."""
186
# https://bugs.launchpad.net/launchpad/+bug/397676
187
supports_merge_proposal_labels = False
189
supports_merge_proposal_commit_message = True
191
def __init__(self, staging=False):
192
self._staging = staging
194
lp_base_url = uris.STAGING_SERVICE_ROOT
196
lp_base_url = uris.LPNET_SERVICE_ROOT
197
self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
201
return lp_api.uris.web_root_for_service_root(
202
str(self.launchpad._root_uri))
205
return "Launchpad(staging=%s)" % self._staging
207
def hosts(self, branch):
208
# TODO(jelmer): staging vs non-staging?
209
return plausible_launchpad_url(branch.user_url)
212
def probe_from_url(cls, url, possible_transports=None):
213
if plausible_launchpad_url(url):
215
raise UnsupportedHoster(url)
217
def _get_lp_git_ref_from_branch(self, branch):
218
url, params = urlutils.split_segment_parameters(branch.user_url)
219
(scheme, user, password, host, port, path) = urlutils.parse_url(
221
repo_lp = self.launchpad.git_repositories.getByPath(
222
path=path.strip('/'))
224
ref_path = params['ref']
226
branch_name = params.get('branch', branch.name)
228
ref_path = 'refs/heads/%s' % branch_name
230
ref_path = repo_lp.default_branch
231
ref_lp = repo_lp.getRefByPath(path=ref_path)
232
return (repo_lp, ref_lp)
234
def _get_lp_bzr_branch_from_branch(self, branch):
235
return self.launchpad.branches.getByUrl(
236
url=urlutils.unescape(branch.user_url))
238
def _get_derived_git_path(self, base_path, owner, project):
239
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
241
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
242
if project.startswith('~'):
243
project = '/'.join(base_path.split('/')[1:])
244
# TODO(jelmer): Surely there is a better way of creating one of these
246
return "~%s/%s" % (owner, project)
248
def _publish_git(self, local_branch, base_path, name, owner, project=None,
249
revision_id=None, overwrite=False, allow_lossy=True):
250
to_path = self._get_derived_git_path(base_path, owner, project)
251
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
253
dir_to = controldir.ControlDir.open_from_transport(to_transport)
254
except errors.NotBranchError:
255
# Didn't find anything
260
br_to = local_branch.create_clone_on_transport(
261
to_transport, revision_id=revision_id, name=name)
262
except errors.NoRoundtrippingSupport:
263
br_to = local_branch.create_clone_on_transport(
264
to_transport, revision_id=revision_id, name=name,
268
dir_to = dir_to.push_branch(
269
local_branch, revision_id, overwrite=overwrite, name=name)
270
except errors.NoRoundtrippingSupport:
273
dir_to = dir_to.push_branch(
274
local_branch, revision_id, overwrite=overwrite, name=name,
276
br_to = dir_to.target_branch
278
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
280
def _get_derived_bzr_path(self, base_branch, name, owner, project):
282
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
283
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
284
# TODO(jelmer): Surely there is a better way of creating one of these
286
return "~%s/%s/%s" % (owner, project, name)
288
def get_push_url(self, branch):
289
(vcs, user, password, path, params) = self._split_url(branch.user_url)
291
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
292
return branch_lp.bzr_identity
294
return urlutils.join_segment_parameters(
295
"git+ssh://git.launchpad.net/" + path, params)
299
def _publish_bzr(self, local_branch, base_branch, name, owner,
300
project=None, revision_id=None, overwrite=False,
302
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
303
to_transport = get_transport("lp:" + to_path)
305
dir_to = controldir.ControlDir.open_from_transport(to_transport)
306
except errors.NotBranchError:
307
# Didn't find anything
311
br_to = local_branch.create_clone_on_transport(
312
to_transport, revision_id=revision_id)
314
br_to = dir_to.push_branch(
315
local_branch, revision_id, overwrite=overwrite).target_branch
316
return br_to, ("https://code.launchpad.net/" + to_path)
318
def _split_url(self, url):
319
url, params = urlutils.split_segment_parameters(url)
320
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
321
path = path.strip('/')
322
if host.startswith('bazaar.'):
324
elif host.startswith('git.'):
327
raise ValueError("unknown host %s" % host)
328
return (vcs, user, password, path, params)
330
def publish_derived(self, local_branch, base_branch, name, project=None,
331
owner=None, revision_id=None, overwrite=False,
333
"""Publish a branch to the site, derived from base_branch.
335
:param base_branch: branch to derive the new branch from
336
:param new_branch: branch to publish
337
:param name: Name of the new branch on the remote host
338
:param project: Optional project name
339
:param owner: Optional owner
340
:return: resulting branch
343
owner = self.launchpad.me.name
344
(base_vcs, base_user, base_password, base_path,
345
base_params) = self._split_url(base_branch.user_url)
346
# TODO(jelmer): Prevent publishing to development focus
347
if base_vcs == 'bzr':
348
return self._publish_bzr(
349
local_branch, base_branch, name, project=project, owner=owner,
350
revision_id=revision_id, overwrite=overwrite,
351
allow_lossy=allow_lossy)
352
elif base_vcs == 'git':
353
return self._publish_git(
354
local_branch, base_path, name, project=project, owner=owner,
355
revision_id=revision_id, overwrite=overwrite,
356
allow_lossy=allow_lossy)
358
raise AssertionError('not a valid Launchpad URL')
360
def get_derived_branch(self, base_branch, name, project=None, owner=None):
362
owner = self.launchpad.me.name
363
(base_vcs, base_user, base_password, base_path,
364
base_params) = self._split_url(base_branch.user_url)
365
if base_vcs == 'bzr':
366
to_path = self._get_derived_bzr_path(
367
base_branch, name, owner, project)
368
return _mod_branch.Branch.open("lp:" + to_path)
369
elif base_vcs == 'git':
370
to_path = self._get_derived_git_path(
371
base_path.strip('/'), owner, project)
372
to_url = urlutils.join_segment_parameters(
373
"git+ssh://git.launchpad.net/" + to_path,
375
return _mod_branch.Branch.open(to_url)
377
raise AssertionError('not a valid Launchpad URL')
379
def iter_proposals(self, source_branch, target_branch, status='open'):
380
(base_vcs, base_user, base_password, base_path,
381
base_params) = self._split_url(target_branch.user_url)
382
statuses = status_to_lp_mp_statuses(status)
383
if base_vcs == 'bzr':
384
target_branch_lp = self.launchpad.branches.getByUrl(
385
url=target_branch.user_url)
386
source_branch_lp = self.launchpad.branches.getByUrl(
387
url=source_branch.user_url)
388
for mp in target_branch_lp.getMergeProposals(status=statuses):
389
if mp.source_branch_link != source_branch_lp.self_link:
391
yield LaunchpadMergeProposal(mp)
392
elif base_vcs == 'git':
393
(source_repo_lp, source_branch_lp) = (
394
self._get_lp_git_ref_from_branch(source_branch))
395
(target_repo_lp, target_branch_lp) = (
396
self._get_lp_git_ref_from_branch(target_branch))
397
for mp in target_branch_lp.getMergeProposals(status=statuses):
398
if (target_branch_lp.path != mp.target_git_path or
399
target_repo_lp != mp.target_git_repository or
400
source_branch_lp.path != mp.source_git_path or
401
source_repo_lp != mp.source_git_repository):
403
yield LaunchpadMergeProposal(mp)
405
raise AssertionError('not a valid Launchpad URL')
407
def get_proposer(self, source_branch, target_branch):
408
(base_vcs, base_user, base_password, base_path,
409
base_params) = self._split_url(target_branch.user_url)
410
if base_vcs == 'bzr':
411
return LaunchpadBazaarMergeProposalBuilder(
412
self, source_branch, target_branch)
413
elif base_vcs == 'git':
414
return LaunchpadGitMergeProposalBuilder(
415
self, source_branch, target_branch)
417
raise AssertionError('not a valid Launchpad URL')
420
def iter_instances(cls):
423
def iter_my_proposals(self, status='open'):
424
statuses = status_to_lp_mp_statuses(status)
425
for mp in self.launchpad.me.getMergeProposals(status=statuses):
426
yield LaunchpadMergeProposal(mp)
428
def get_proposal_by_url(self, url):
429
# Launchpad doesn't have a way to find a merge proposal by URL.
430
(scheme, user, password, host, port, path) = urlutils.parse_url(
432
LAUNCHPAD_CODE_DOMAINS = [
433
('code.%s' % domain) for domain in lp_api.LAUNCHPAD_DOMAINS.values()]
434
if host not in LAUNCHPAD_CODE_DOMAINS:
435
raise UnsupportedHoster(url)
436
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
438
# See https://api.launchpad.net/devel/#branch_merge_proposal
440
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
441
api_url = str(self.launchpad._root_uri) + path
442
mp = self.launchpad.load(api_url)
443
return LaunchpadMergeProposal(mp)
446
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
448
def __init__(self, lp_host, source_branch, target_branch,
449
staging=None, approve=None, fixes=None):
452
:param source_branch: The branch to propose for merging.
453
:param target_branch: The branch to merge into.
454
:param staging: If True, propose the merge against staging instead of
456
:param approve: If True, mark the new proposal as approved immediately.
457
This is useful when a project permits some things to be approved
458
by the submitter (e.g. merges between release and deployment
461
self.lp_host = lp_host
462
self.launchpad = lp_host.launchpad
463
self.source_branch = source_branch
464
self.source_branch_lp = self.launchpad.branches.getByUrl(
465
url=source_branch.user_url)
466
if target_branch is None:
467
self.target_branch_lp = self.source_branch_lp.get_target()
468
self.target_branch = _mod_branch.Branch.open(
469
self.target_branch_lp.bzr_identity)
471
self.target_branch = target_branch
472
self.target_branch_lp = self.launchpad.branches.getByUrl(
473
url=target_branch.user_url)
474
self.approve = approve
477
def get_infotext(self):
478
"""Determine the initial comment for the merge proposal."""
479
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
480
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
483
def get_initial_body(self):
484
"""Get a body for the proposal for the user to modify.
486
:return: a str or None.
488
if not self.hooks['merge_proposal_body']:
491
def list_modified_files():
492
lca_tree = self.source_branch_lp.find_lca_tree(
493
self.target_branch_lp)
494
source_tree = self.source_branch.basis_tree()
495
files = modified_files(lca_tree, source_tree)
497
with self.target_branch.lock_read(), \
498
self.source_branch.lock_read():
500
for hook in self.hooks['merge_proposal_body']:
502
'target_branch': self.target_branch_lp.bzr_identity,
503
'modified_files_callback': list_modified_files,
508
def check_proposal(self):
509
"""Check that the submission is sensible."""
510
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
511
raise errors.BzrCommandError(
512
'Source and target branches must be different.')
513
for mp in self.source_branch_lp.landing_targets:
514
if mp.queue_status in ('Merged', 'Rejected'):
516
if mp.target_branch.self_link == self.target_branch_lp.self_link:
517
raise MergeProposalExists(lp_api.canonical_url(mp))
519
def approve_proposal(self, mp):
520
with self.source_branch.lock_read():
524
subject='', # Use the default subject.
525
content=u"Rubberstamp! Proposer approves of own proposal.")
526
_call_webservice(mp.setStatus, status=u'Approved',
527
revid=self.source_branch.last_revision())
529
def create_proposal(self, description, reviewers=None, labels=None,
530
prerequisite_branch=None, commit_message=None):
531
"""Perform the submission."""
533
raise LabelsUnsupported(self)
534
if prerequisite_branch is not None:
535
prereq = self.launchpad.branches.getByUrl(
536
url=prerequisite_branch.user_url)
539
if reviewers is None:
542
mp = _call_webservice(
543
self.source_branch_lp.createMergeProposal,
544
target_branch=self.target_branch_lp,
545
prerequisite_branch=prereq,
546
initial_comment=description.strip(),
547
commit_message=commit_message,
548
reviewers=[self.launchpad.people[reviewer].self_link
549
for reviewer in reviewers],
550
review_types=['' for reviewer in reviewers])
551
except WebserviceFailure as e:
553
if (b'There is already a branch merge proposal '
554
b'registered for branch ') in e.message:
555
raise MergeProposalExists(self.source_branch.user_url)
559
self.approve_proposal(mp)
561
if self.fixes.startswith('lp:'):
562
self.fixes = self.fixes[3:]
565
bug=self.launchpad.bugs[int(self.fixes)])
566
return LaunchpadMergeProposal(mp)
569
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
571
def __init__(self, lp_host, source_branch, target_branch,
572
staging=None, approve=None, fixes=None):
575
:param source_branch: The branch to propose for merging.
576
:param target_branch: The branch to merge into.
577
:param staging: If True, propose the merge against staging instead of
579
:param approve: If True, mark the new proposal as approved immediately.
580
This is useful when a project permits some things to be approved
581
by the submitter (e.g. merges between release and deployment
584
self.lp_host = lp_host
585
self.launchpad = lp_host.launchpad
586
self.source_branch = source_branch
587
(self.source_repo_lp,
588
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
590
if target_branch is None:
591
self.target_branch_lp = self.source_branch.get_target()
592
self.target_branch = _mod_branch.Branch.open(
593
self.target_branch_lp.git_https_url)
595
self.target_branch = target_branch
596
(self.target_repo_lp, self.target_branch_lp) = (
597
self.lp_host._get_lp_git_ref_from_branch(target_branch))
598
self.approve = approve
601
def get_infotext(self):
602
"""Determine the initial comment for the merge proposal."""
603
info = ["Source: %s\n" % self.source_branch.user_url]
604
info.append("Target: %s\n" % self.target_branch.user_url)
607
def get_initial_body(self):
608
"""Get a body for the proposal for the user to modify.
610
:return: a str or None.
612
if not self.hooks['merge_proposal_body']:
615
def list_modified_files():
616
lca_tree = self.source_branch_lp.find_lca_tree(
617
self.target_branch_lp)
618
source_tree = self.source_branch.basis_tree()
619
files = modified_files(lca_tree, source_tree)
621
with self.target_branch.lock_read(), \
622
self.source_branch.lock_read():
624
for hook in self.hooks['merge_proposal_body']:
626
'target_branch': self.target_branch,
627
'modified_files_callback': list_modified_files,
632
def check_proposal(self):
633
"""Check that the submission is sensible."""
634
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
635
raise errors.BzrCommandError(
636
'Source and target branches must be different.')
637
for mp in self.source_branch_lp.landing_targets:
638
if mp.queue_status in ('Merged', 'Rejected'):
640
if mp.target_branch.self_link == self.target_branch_lp.self_link:
641
raise MergeProposalExists(lp_api.canonical_url(mp))
643
def approve_proposal(self, mp):
644
with self.source_branch.lock_read():
648
subject='', # Use the default subject.
649
content=u"Rubberstamp! Proposer approves of own proposal.")
651
mp.setStatus, status=u'Approved',
652
revid=self.source_branch.last_revision())
654
def create_proposal(self, description, reviewers=None, labels=None,
655
prerequisite_branch=None, commit_message=None):
656
"""Perform the submission."""
658
raise LabelsUnsupported(self)
659
if prerequisite_branch is not None:
660
(prereq_repo_lp, prereq_branch_lp) = (
661
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
663
prereq_branch_lp = None
664
if reviewers is None:
667
mp = _call_webservice(
668
self.source_branch_lp.createMergeProposal,
669
merge_target=self.target_branch_lp,
670
merge_prerequisite=prereq_branch_lp,
671
initial_comment=description.strip(),
672
commit_message=commit_message,
674
reviewers=[self.launchpad.people[reviewer].self_link
675
for reviewer in reviewers],
676
review_types=[None for reviewer in reviewers])
677
except WebserviceFailure as e:
679
if ('There is already a branch merge proposal '
680
'registered for branch ') in e.message:
681
raise MergeProposalExists(self.source_branch.user_url)
684
self.approve_proposal(mp)
686
if self.fixes.startswith('lp:'):
687
self.fixes = self.fixes[3:]
690
bug=self.launchpad.bugs[int(self.fixes)])
691
return LaunchpadMergeProposal(mp)
694
def modified_files(old_tree, new_tree):
695
"""Return a list of paths in the new tree with modified contents."""
696
for change in new_tree.iter_changes(old_tree):
697
if change.changed_content and change.kind[1] == 'file':