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')
141
return (self._mp.queue_status in ('Rejected', 'Superseded'))
144
self._mp.setStatus(status='Needs review')
146
def get_description(self):
147
return self._mp.description
149
def set_description(self, description):
150
self._mp.description = description
153
def get_commit_message(self):
154
return self._mp.commit_message
156
def set_commit_message(self, commit_message):
157
self._mp.commit_message = commit_message
161
self._mp.setStatus(status='Rejected')
163
def can_be_merged(self):
164
if not self._mp.preview_diff:
167
return not bool(self._mp.preview_diff.conflicts)
169
def merge(self, commit_message=None):
170
target_branch = _mod_branch.Branch.open(
171
self.get_target_branch_url())
172
source_branch = _mod_branch.Branch.open(
173
self.get_source_branch_url())
174
# TODO(jelmer): Ideally this would use a memorytree, but merge doesn't
176
# tree = target_branch.create_memorytree()
177
tmpdir = tempfile.mkdtemp()
179
tree = target_branch.create_checkout(
180
to_location=tmpdir, lightweight=True)
181
tree.merge_from_branch(source_branch)
182
tree.commit(commit_message or self._mp.commit_message)
184
shutil.rmtree(tmpdir)
187
class Launchpad(Hoster):
188
"""The Launchpad hosting service."""
192
# https://bugs.launchpad.net/launchpad/+bug/397676
193
supports_merge_proposal_labels = False
195
supports_merge_proposal_commit_message = True
197
def __init__(self, staging=False):
198
self._staging = staging
200
lp_base_url = uris.STAGING_SERVICE_ROOT
202
lp_base_url = uris.LPNET_SERVICE_ROOT
203
self.launchpad = lp_api.connect_launchpad(lp_base_url, version='devel')
207
return lp_api.uris.web_root_for_service_root(
208
str(self.launchpad._root_uri))
211
return "Launchpad(staging=%s)" % self._staging
213
def hosts(self, branch):
214
# TODO(jelmer): staging vs non-staging?
215
return plausible_launchpad_url(branch.user_url)
218
def probe_from_url(cls, url, possible_transports=None):
219
if plausible_launchpad_url(url):
221
raise UnsupportedHoster(url)
223
def _get_lp_git_ref_from_branch(self, branch):
224
url, params = urlutils.split_segment_parameters(branch.user_url)
225
(scheme, user, password, host, port, path) = urlutils.parse_url(
227
repo_lp = self.launchpad.git_repositories.getByPath(
228
path=path.strip('/'))
230
ref_path = params['ref']
232
branch_name = params.get('branch', branch.name)
234
ref_path = 'refs/heads/%s' % branch_name
236
ref_path = repo_lp.default_branch
237
ref_lp = repo_lp.getRefByPath(path=ref_path)
238
return (repo_lp, ref_lp)
240
def _get_lp_bzr_branch_from_branch(self, branch):
241
return self.launchpad.branches.getByUrl(
242
url=urlutils.unescape(branch.user_url))
244
def _get_derived_git_path(self, base_path, owner, project):
245
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
247
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
248
if project.startswith('~'):
249
project = '/'.join(base_path.split('/')[1:])
250
# TODO(jelmer): Surely there is a better way of creating one of these
252
return "~%s/%s" % (owner, project)
254
def _publish_git(self, local_branch, base_path, name, owner, project=None,
255
revision_id=None, overwrite=False, allow_lossy=True):
256
to_path = self._get_derived_git_path(base_path, owner, project)
257
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
259
dir_to = controldir.ControlDir.open_from_transport(to_transport)
260
except errors.NotBranchError:
261
# Didn't find anything
266
br_to = local_branch.create_clone_on_transport(
267
to_transport, revision_id=revision_id, name=name)
268
except errors.NoRoundtrippingSupport:
269
br_to = local_branch.create_clone_on_transport(
270
to_transport, revision_id=revision_id, name=name,
274
dir_to = dir_to.push_branch(
275
local_branch, revision_id, overwrite=overwrite, name=name)
276
except errors.NoRoundtrippingSupport:
279
dir_to = dir_to.push_branch(
280
local_branch, revision_id, overwrite=overwrite, name=name,
282
br_to = dir_to.target_branch
284
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
286
def _get_derived_bzr_path(self, base_branch, name, owner, project):
288
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
289
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
290
# TODO(jelmer): Surely there is a better way of creating one of these
292
return "~%s/%s/%s" % (owner, project, name)
294
def get_push_url(self, branch):
295
(vcs, user, password, path, params) = self._split_url(branch.user_url)
297
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
298
return branch_lp.bzr_identity
300
return urlutils.join_segment_parameters(
301
"git+ssh://git.launchpad.net/" + path, params)
305
def _publish_bzr(self, local_branch, base_branch, name, owner,
306
project=None, revision_id=None, overwrite=False,
308
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
309
to_transport = get_transport("lp:" + to_path)
311
dir_to = controldir.ControlDir.open_from_transport(to_transport)
312
except errors.NotBranchError:
313
# Didn't find anything
317
br_to = local_branch.create_clone_on_transport(
318
to_transport, revision_id=revision_id)
320
br_to = dir_to.push_branch(
321
local_branch, revision_id, overwrite=overwrite).target_branch
322
return br_to, ("https://code.launchpad.net/" + to_path)
324
def _split_url(self, url):
325
url, params = urlutils.split_segment_parameters(url)
326
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
327
path = path.strip('/')
328
if host.startswith('bazaar.'):
330
elif host.startswith('git.'):
333
raise ValueError("unknown host %s" % host)
334
return (vcs, user, password, path, params)
336
def publish_derived(self, local_branch, base_branch, name, project=None,
337
owner=None, revision_id=None, overwrite=False,
339
"""Publish a branch to the site, derived from base_branch.
341
:param base_branch: branch to derive the new branch from
342
:param new_branch: branch to publish
343
:param name: Name of the new branch on the remote host
344
:param project: Optional project name
345
:param owner: Optional owner
346
:return: resulting branch
349
owner = self.launchpad.me.name
350
(base_vcs, base_user, base_password, base_path,
351
base_params) = self._split_url(base_branch.user_url)
352
# TODO(jelmer): Prevent publishing to development focus
353
if base_vcs == 'bzr':
354
return self._publish_bzr(
355
local_branch, base_branch, name, project=project, owner=owner,
356
revision_id=revision_id, overwrite=overwrite,
357
allow_lossy=allow_lossy)
358
elif base_vcs == 'git':
359
return self._publish_git(
360
local_branch, base_path, name, project=project, owner=owner,
361
revision_id=revision_id, overwrite=overwrite,
362
allow_lossy=allow_lossy)
364
raise AssertionError('not a valid Launchpad URL')
366
def get_derived_branch(self, base_branch, name, project=None, owner=None):
368
owner = self.launchpad.me.name
369
(base_vcs, base_user, base_password, base_path,
370
base_params) = self._split_url(base_branch.user_url)
371
if base_vcs == 'bzr':
372
to_path = self._get_derived_bzr_path(
373
base_branch, name, owner, project)
374
return _mod_branch.Branch.open("lp:" + to_path)
375
elif base_vcs == 'git':
376
to_path = self._get_derived_git_path(
377
base_path.strip('/'), owner, project)
378
to_url = urlutils.join_segment_parameters(
379
"git+ssh://git.launchpad.net/" + to_path,
381
return _mod_branch.Branch.open(to_url)
383
raise AssertionError('not a valid Launchpad URL')
385
def iter_proposals(self, source_branch, target_branch, status='open'):
386
(base_vcs, base_user, base_password, base_path,
387
base_params) = self._split_url(target_branch.user_url)
388
statuses = status_to_lp_mp_statuses(status)
389
if base_vcs == 'bzr':
390
target_branch_lp = self.launchpad.branches.getByUrl(
391
url=target_branch.user_url)
392
source_branch_lp = self.launchpad.branches.getByUrl(
393
url=source_branch.user_url)
394
for mp in target_branch_lp.getMergeProposals(status=statuses):
395
if mp.source_branch_link != source_branch_lp.self_link:
397
yield LaunchpadMergeProposal(mp)
398
elif base_vcs == 'git':
399
(source_repo_lp, source_branch_lp) = (
400
self._get_lp_git_ref_from_branch(source_branch))
401
(target_repo_lp, target_branch_lp) = (
402
self._get_lp_git_ref_from_branch(target_branch))
403
for mp in target_branch_lp.getMergeProposals(status=statuses):
404
if (target_branch_lp.path != mp.target_git_path or
405
target_repo_lp != mp.target_git_repository or
406
source_branch_lp.path != mp.source_git_path or
407
source_repo_lp != mp.source_git_repository):
409
yield LaunchpadMergeProposal(mp)
411
raise AssertionError('not a valid Launchpad URL')
413
def get_proposer(self, source_branch, target_branch):
414
(base_vcs, base_user, base_password, base_path,
415
base_params) = self._split_url(target_branch.user_url)
416
if base_vcs == 'bzr':
417
return LaunchpadBazaarMergeProposalBuilder(
418
self, source_branch, target_branch)
419
elif base_vcs == 'git':
420
return LaunchpadGitMergeProposalBuilder(
421
self, source_branch, target_branch)
423
raise AssertionError('not a valid Launchpad URL')
426
def iter_instances(cls):
429
def iter_my_proposals(self, status='open'):
430
statuses = status_to_lp_mp_statuses(status)
431
for mp in self.launchpad.me.getMergeProposals(status=statuses):
432
yield LaunchpadMergeProposal(mp)
434
def get_proposal_by_url(self, url):
435
# Launchpad doesn't have a way to find a merge proposal by URL.
436
(scheme, user, password, host, port, path) = urlutils.parse_url(
438
LAUNCHPAD_CODE_DOMAINS = [
439
('code.%s' % domain) for domain in lp_api.LAUNCHPAD_DOMAINS.values()]
440
if host not in LAUNCHPAD_CODE_DOMAINS:
441
raise UnsupportedHoster(url)
442
# TODO(jelmer): Check if this is a launchpad URL. Otherwise, raise
444
# See https://api.launchpad.net/devel/#branch_merge_proposal
446
# https://api.launchpad.net/devel/~<author.name>/<project.name>/<branch.name>/+merge/<id>
447
api_url = str(self.launchpad._root_uri) + path
448
mp = self.launchpad.load(api_url)
449
return LaunchpadMergeProposal(mp)
452
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
454
def __init__(self, lp_host, source_branch, target_branch,
455
staging=None, approve=None, fixes=None):
458
:param source_branch: The branch to propose for merging.
459
:param target_branch: The branch to merge into.
460
:param staging: If True, propose the merge against staging instead of
462
:param approve: If True, mark the new proposal as approved immediately.
463
This is useful when a project permits some things to be approved
464
by the submitter (e.g. merges between release and deployment
467
self.lp_host = lp_host
468
self.launchpad = lp_host.launchpad
469
self.source_branch = source_branch
470
self.source_branch_lp = self.launchpad.branches.getByUrl(
471
url=source_branch.user_url)
472
if target_branch is None:
473
self.target_branch_lp = self.source_branch_lp.get_target()
474
self.target_branch = _mod_branch.Branch.open(
475
self.target_branch_lp.bzr_identity)
477
self.target_branch = target_branch
478
self.target_branch_lp = self.launchpad.branches.getByUrl(
479
url=target_branch.user_url)
480
self.approve = approve
483
def get_infotext(self):
484
"""Determine the initial comment for the merge proposal."""
485
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
486
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
489
def get_initial_body(self):
490
"""Get a body for the proposal for the user to modify.
492
:return: a str or None.
494
if not self.hooks['merge_proposal_body']:
497
def list_modified_files():
498
lca_tree = self.source_branch_lp.find_lca_tree(
499
self.target_branch_lp)
500
source_tree = self.source_branch.basis_tree()
501
files = modified_files(lca_tree, source_tree)
503
with self.target_branch.lock_read(), \
504
self.source_branch.lock_read():
506
for hook in self.hooks['merge_proposal_body']:
508
'target_branch': self.target_branch_lp.bzr_identity,
509
'modified_files_callback': list_modified_files,
514
def check_proposal(self):
515
"""Check that the submission is sensible."""
516
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
517
raise errors.BzrCommandError(
518
'Source and target branches must be different.')
519
for mp in self.source_branch_lp.landing_targets:
520
if mp.queue_status in ('Merged', 'Rejected'):
522
if mp.target_branch.self_link == self.target_branch_lp.self_link:
523
raise MergeProposalExists(lp_api.canonical_url(mp))
525
def approve_proposal(self, mp):
526
with self.source_branch.lock_read():
530
subject='', # Use the default subject.
531
content=u"Rubberstamp! Proposer approves of own proposal.")
532
_call_webservice(mp.setStatus, status=u'Approved',
533
revid=self.source_branch.last_revision())
535
def create_proposal(self, description, reviewers=None, labels=None,
536
prerequisite_branch=None, commit_message=None):
537
"""Perform the submission."""
539
raise LabelsUnsupported(self)
540
if prerequisite_branch is not None:
541
prereq = self.launchpad.branches.getByUrl(
542
url=prerequisite_branch.user_url)
545
if reviewers is None:
549
for reviewer in reviewers:
551
reviewer_obj = self.launchpad.people.getByEmail(email=reviewer)
553
reviewer_obj = self.launchpad.people[reviewer]
554
reviewer_objs.append(reviewer_obj)
556
mp = _call_webservice(
557
self.source_branch_lp.createMergeProposal,
558
target_branch=self.target_branch_lp,
559
prerequisite_branch=prereq,
560
initial_comment=description.strip(),
561
commit_message=commit_message,
562
reviewers=[reviewer.self_link for reviewer in reviewer_objs],
563
review_types=['' for reviewer in reviewer_objs])
564
except WebserviceFailure as e:
566
if (b'There is already a branch merge proposal '
567
b'registered for branch ') in e.message:
568
raise MergeProposalExists(self.source_branch.user_url)
572
self.approve_proposal(mp)
574
if self.fixes.startswith('lp:'):
575
self.fixes = self.fixes[3:]
578
bug=self.launchpad.bugs[int(self.fixes)])
579
return LaunchpadMergeProposal(mp)
582
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
584
def __init__(self, lp_host, source_branch, target_branch,
585
staging=None, approve=None, fixes=None):
588
:param source_branch: The branch to propose for merging.
589
:param target_branch: The branch to merge into.
590
:param staging: If True, propose the merge against staging instead of
592
:param approve: If True, mark the new proposal as approved immediately.
593
This is useful when a project permits some things to be approved
594
by the submitter (e.g. merges between release and deployment
597
self.lp_host = lp_host
598
self.launchpad = lp_host.launchpad
599
self.source_branch = source_branch
600
(self.source_repo_lp,
601
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
603
if target_branch is None:
604
self.target_branch_lp = self.source_branch.get_target()
605
self.target_branch = _mod_branch.Branch.open(
606
self.target_branch_lp.git_https_url)
608
self.target_branch = target_branch
609
(self.target_repo_lp, self.target_branch_lp) = (
610
self.lp_host._get_lp_git_ref_from_branch(target_branch))
611
self.approve = approve
614
def get_infotext(self):
615
"""Determine the initial comment for the merge proposal."""
616
info = ["Source: %s\n" % self.source_branch.user_url]
617
info.append("Target: %s\n" % self.target_branch.user_url)
620
def get_initial_body(self):
621
"""Get a body for the proposal for the user to modify.
623
:return: a str or None.
625
if not self.hooks['merge_proposal_body']:
628
def list_modified_files():
629
lca_tree = self.source_branch_lp.find_lca_tree(
630
self.target_branch_lp)
631
source_tree = self.source_branch.basis_tree()
632
files = modified_files(lca_tree, source_tree)
634
with self.target_branch.lock_read(), \
635
self.source_branch.lock_read():
637
for hook in self.hooks['merge_proposal_body']:
639
'target_branch': self.target_branch,
640
'modified_files_callback': list_modified_files,
645
def check_proposal(self):
646
"""Check that the submission is sensible."""
647
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
648
raise errors.BzrCommandError(
649
'Source and target branches must be different.')
650
for mp in self.source_branch_lp.landing_targets:
651
if mp.queue_status in ('Merged', 'Rejected'):
653
if mp.target_branch.self_link == self.target_branch_lp.self_link:
654
raise MergeProposalExists(lp_api.canonical_url(mp))
656
def approve_proposal(self, mp):
657
with self.source_branch.lock_read():
661
subject='', # Use the default subject.
662
content=u"Rubberstamp! Proposer approves of own proposal.")
664
mp.setStatus, status=u'Approved',
665
revid=self.source_branch.last_revision())
667
def create_proposal(self, description, reviewers=None, labels=None,
668
prerequisite_branch=None, commit_message=None):
669
"""Perform the submission."""
671
raise LabelsUnsupported(self)
672
if prerequisite_branch is not None:
673
(prereq_repo_lp, prereq_branch_lp) = (
674
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
676
prereq_branch_lp = None
677
if reviewers is None:
680
mp = _call_webservice(
681
self.source_branch_lp.createMergeProposal,
682
merge_target=self.target_branch_lp,
683
merge_prerequisite=prereq_branch_lp,
684
initial_comment=description.strip(),
685
commit_message=commit_message,
687
reviewers=[self.launchpad.people[reviewer].self_link
688
for reviewer in reviewers],
689
review_types=[None for reviewer in reviewers])
690
except WebserviceFailure as e:
692
if ('There is already a branch merge proposal '
693
'registered for branch ') in e.message:
694
raise MergeProposalExists(self.source_branch.user_url)
697
self.approve_proposal(mp)
699
if self.fixes.startswith('lp:'):
700
self.fixes = self.fixes[3:]
703
bug=self.launchpad.bugs[int(self.fixes)])
704
return LaunchpadMergeProposal(mp)
707
def modified_files(old_tree, new_tree):
708
"""Return a list of paths in the new tree with modified contents."""
709
for change in new_tree.iter_changes(old_tree):
710
if change.changed_content and change.kind[1] == 'file':