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
24
from .propose import (
34
branch as _mod_branch,
40
from ...git.refs import ref_to_branch_name
41
from ...lazy_import import lazy_import
42
lazy_import(globals(), """
43
from breezy.plugins.launchpad import (
47
from launchpadlib import uris
49
from ...transport import get_transport
52
# TODO(jelmer): Make selection of launchpad staging a configuration option.
54
def status_to_lp_mp_statuses(status):
56
if status in ('open', 'all'):
61
'Code failed to merge',
63
if status in ('closed', 'all'):
64
statuses.extend(['Rejected', 'Superseded'])
65
if status in ('merged', 'all'):
66
statuses.append('Merged')
70
def plausible_launchpad_url(url):
73
if url.startswith('lp:'):
75
regex = re.compile('([a-z]*\+)*(bzr\+ssh|http|ssh|git|https)'
76
'://(bazaar|git).*\.launchpad\.net')
77
return bool(regex.match(url))
80
class WebserviceFailure(Exception):
82
def __init__(self, message):
83
self.message = message
86
def _call_webservice(call, *args, **kwargs):
87
"""Make a call to the webservice, wrapping failures.
89
:param call: The call to make.
90
:param *args: *args for the call.
91
:param **kwargs: **kwargs for the call.
92
:return: The result of calling call(*args, *kwargs).
94
from lazr.restfulclient import errors as restful_errors
96
return call(*args, **kwargs)
97
except restful_errors.HTTPError as e:
99
for line in e.content.splitlines():
100
if line.startswith(b'Traceback (most recent call last):'):
102
error_lines.append(line)
103
raise WebserviceFailure(b''.join(error_lines))
106
class LaunchpadMergeProposal(MergeProposal):
108
def __init__(self, mp):
111
def get_source_branch_url(self):
112
if self._mp.source_branch:
113
return self._mp.source_branch.bzr_identity
115
branch_name = ref_to_branch_name(
116
self._mp.source_git_path.encode('utf-8'))
117
return urlutils.join_segment_parameters(
118
self._mp.source_git_repository.git_identity,
119
{"branch": branch_name})
121
def get_target_branch_url(self):
122
if self._mp.target_branch:
123
return self._mp.target_branch.bzr_identity
125
branch_name = ref_to_branch_name(
126
self._mp.target_git_path.encode('utf-8'))
127
return urlutils.join_segment_parameters(
128
self._mp.target_git_repository.git_identity,
129
{"branch": branch_name})
133
return lp_api.canonical_url(self._mp)
136
return (self._mp.queue_status == 'Merged')
138
def get_description(self):
139
return self._mp.description
141
def set_description(self, description):
142
self._mp.description = description
145
def get_commit_message(self):
146
return self._mp.commit_message
148
def set_commit_message(self, commit_message):
149
self._mp.commit_message = commit_message
153
self._mp.setStatus(status='Rejected')
156
class Launchpad(Hoster):
157
"""The Launchpad hosting service."""
161
# https://bugs.launchpad.net/launchpad/+bug/397676
162
supports_merge_proposal_labels = False
164
supports_merge_proposal_commit_message = True
166
def __init__(self, staging=False):
167
self._staging = staging
169
lp_base_url = uris.STAGING_SERVICE_ROOT
171
lp_base_url = uris.LPNET_SERVICE_ROOT
172
self.launchpad = lp_api.connect_launchpad(lp_base_url)
176
return lp_api.uris.web_root_for_service_root(
177
str(self.launchpad._root_uri))
180
return "Launchpad(staging=%s)" % self._staging
182
def hosts(self, branch):
183
# TODO(jelmer): staging vs non-staging?
184
return plausible_launchpad_url(branch.user_url)
187
def probe_from_url(cls, url, possible_transports=None):
188
if plausible_launchpad_url(url):
190
raise UnsupportedHoster(url)
192
def _get_lp_git_ref_from_branch(self, branch):
193
url, params = urlutils.split_segment_parameters(branch.user_url)
194
(scheme, user, password, host, port, path) = urlutils.parse_url(
196
repo_lp = self.launchpad.git_repositories.getByPath(
197
path=path.strip('/'))
199
ref_path = params['ref']
201
branch_name = params.get('branch', branch.name)
203
ref_path = 'refs/heads/%s' % branch_name
205
ref_path = repo_lp.default_branch
206
ref_lp = repo_lp.getRefByPath(path=ref_path)
207
return (repo_lp, ref_lp)
209
def _get_lp_bzr_branch_from_branch(self, branch):
210
return self.launchpad.branches.getByUrl(
211
url=urlutils.unescape(branch.user_url))
213
def _get_derived_git_path(self, base_path, owner, project):
214
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
216
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
217
if project.startswith('~'):
218
project = '/'.join(base_path.split('/')[1:])
219
# TODO(jelmer): Surely there is a better way of creating one of these
221
return "~%s/%s" % (owner, project)
223
def _publish_git(self, local_branch, base_path, name, owner, project=None,
224
revision_id=None, overwrite=False, allow_lossy=True):
225
to_path = self._get_derived_git_path(base_path, owner, project)
226
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
228
dir_to = controldir.ControlDir.open_from_transport(to_transport)
229
except errors.NotBranchError:
230
# Didn't find anything
235
br_to = local_branch.create_clone_on_transport(
236
to_transport, revision_id=revision_id, name=name)
237
except errors.NoRoundtrippingSupport:
238
br_to = local_branch.create_clone_on_transport(
239
to_transport, revision_id=revision_id, name=name,
243
dir_to = dir_to.push_branch(
244
local_branch, revision_id, overwrite=overwrite, name=name)
245
except errors.NoRoundtrippingSupport:
248
dir_to = dir_to.push_branch(
249
local_branch, revision_id, overwrite=overwrite, name=name,
251
br_to = dir_to.target_branch
253
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
255
def _get_derived_bzr_path(self, base_branch, name, owner, project):
257
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
258
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
259
# TODO(jelmer): Surely there is a better way of creating one of these
261
return "~%s/%s/%s" % (owner, project, name)
263
def get_push_url(self, branch):
264
(vcs, user, password, path, params) = self._split_url(branch.user_url)
266
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
267
return branch_lp.bzr_identity
269
return urlutils.join_segment_parameters(
270
"git+ssh://git.launchpad.net/" + path, params)
274
def _publish_bzr(self, local_branch, base_branch, name, owner,
275
project=None, revision_id=None, overwrite=False,
277
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
278
to_transport = get_transport("lp:" + to_path)
280
dir_to = controldir.ControlDir.open_from_transport(to_transport)
281
except errors.NotBranchError:
282
# Didn't find anything
286
br_to = local_branch.create_clone_on_transport(
287
to_transport, revision_id=revision_id)
289
br_to = dir_to.push_branch(
290
local_branch, revision_id, overwrite=overwrite).target_branch
291
return br_to, ("https://code.launchpad.net/" + to_path)
293
def _split_url(self, url):
294
url, params = urlutils.split_segment_parameters(url)
295
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
296
path = path.strip('/')
297
if host.startswith('bazaar.'):
299
elif host.startswith('git.'):
302
raise ValueError("unknown host %s" % host)
303
return (vcs, user, password, path, params)
305
def publish_derived(self, local_branch, base_branch, name, project=None,
306
owner=None, revision_id=None, overwrite=False,
308
"""Publish a branch to the site, derived from base_branch.
310
:param base_branch: branch to derive the new branch from
311
:param new_branch: branch to publish
312
:param name: Name of the new branch on the remote host
313
:param project: Optional project name
314
:param owner: Optional owner
315
:return: resulting branch
318
owner = self.launchpad.me.name
319
(base_vcs, base_user, base_password, base_path,
320
base_params) = self._split_url(base_branch.user_url)
321
# TODO(jelmer): Prevent publishing to development focus
322
if base_vcs == 'bzr':
323
return self._publish_bzr(
324
local_branch, base_branch, name, project=project, owner=owner,
325
revision_id=revision_id, overwrite=overwrite,
326
allow_lossy=allow_lossy)
327
elif base_vcs == 'git':
328
return self._publish_git(
329
local_branch, base_path, name, project=project, owner=owner,
330
revision_id=revision_id, overwrite=overwrite,
331
allow_lossy=allow_lossy)
333
raise AssertionError('not a valid Launchpad URL')
335
def get_derived_branch(self, base_branch, name, project=None, owner=None):
337
owner = self.launchpad.me.name
338
(base_vcs, base_user, base_password, base_path,
339
base_params) = self._split_url(base_branch.user_url)
340
if base_vcs == 'bzr':
341
to_path = self._get_derived_bzr_path(
342
base_branch, name, owner, project)
343
return _mod_branch.Branch.open("lp:" + to_path)
344
elif base_vcs == 'git':
345
to_path = self._get_derived_git_path(
346
base_path.strip('/'), owner, project)
347
to_url = urlutils.join_segment_parameters(
348
"git+ssh://git.launchpad.net/" + to_path,
350
return _mod_branch.Branch.open(to_url)
352
raise AssertionError('not a valid Launchpad URL')
354
def iter_proposals(self, source_branch, target_branch, status='open'):
355
(base_vcs, base_user, base_password, base_path,
356
base_params) = self._split_url(target_branch.user_url)
357
statuses = status_to_lp_mp_statuses(status)
358
if base_vcs == 'bzr':
359
target_branch_lp = self.launchpad.branches.getByUrl(
360
url=target_branch.user_url)
361
source_branch_lp = self.launchpad.branches.getByUrl(
362
url=source_branch.user_url)
363
for mp in target_branch_lp.getMergeProposals(status=statuses):
364
if mp.source_branch_link != source_branch_lp.self_link:
366
yield LaunchpadMergeProposal(mp)
367
elif base_vcs == 'git':
368
(source_repo_lp, source_branch_lp) = (
369
self._get_lp_git_ref_from_branch(source_branch))
370
(target_repo_lp, target_branch_lp) = (
371
self._get_lp_git_ref_from_branch(target_branch))
372
for mp in target_branch_lp.getMergeProposals(status=statuses):
373
if (target_branch_lp.path != mp.target_git_path or
374
target_repo_lp != mp.target_git_repository or
375
source_branch_lp.path != mp.source_git_path or
376
source_repo_lp != mp.source_git_repository):
378
yield LaunchpadMergeProposal(mp)
380
raise AssertionError('not a valid Launchpad URL')
382
def get_proposer(self, source_branch, target_branch):
383
(base_vcs, base_user, base_password, base_path,
384
base_params) = self._split_url(target_branch.user_url)
385
if base_vcs == 'bzr':
386
return LaunchpadBazaarMergeProposalBuilder(
387
self, source_branch, target_branch)
388
elif base_vcs == 'git':
389
return LaunchpadGitMergeProposalBuilder(
390
self, source_branch, target_branch)
392
raise AssertionError('not a valid Launchpad URL')
395
def iter_instances(cls):
398
def iter_my_proposals(self, status='open'):
399
statuses = status_to_lp_mp_statuses(status)
400
for mp in self.launchpad.me.getMergeProposals(status=statuses):
401
yield LaunchpadMergeProposal(mp)
404
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
406
def __init__(self, lp_host, source_branch, target_branch,
407
staging=None, approve=None, fixes=None):
410
:param source_branch: The branch to propose for merging.
411
:param target_branch: The branch to merge into.
412
:param staging: If True, propose the merge against staging instead of
414
:param approve: If True, mark the new proposal as approved immediately.
415
This is useful when a project permits some things to be approved
416
by the submitter (e.g. merges between release and deployment
419
self.lp_host = lp_host
420
self.launchpad = lp_host.launchpad
421
self.source_branch = source_branch
422
self.source_branch_lp = self.launchpad.branches.getByUrl(
423
url=source_branch.user_url)
424
if target_branch is None:
425
self.target_branch_lp = self.source_branch_lp.get_target()
426
self.target_branch = _mod_branch.Branch.open(
427
self.target_branch_lp.bzr_identity)
429
self.target_branch = target_branch
430
self.target_branch_lp = self.launchpad.branches.getByUrl(
431
url=target_branch.user_url)
432
self.approve = approve
435
def get_infotext(self):
436
"""Determine the initial comment for the merge proposal."""
437
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
438
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
441
def get_initial_body(self):
442
"""Get a body for the proposal for the user to modify.
444
:return: a str or None.
446
if not self.hooks['merge_proposal_body']:
449
def list_modified_files():
450
lca_tree = self.source_branch_lp.find_lca_tree(
451
self.target_branch_lp)
452
source_tree = self.source_branch.basis_tree()
453
files = modified_files(lca_tree, source_tree)
455
with self.target_branch.lock_read(), \
456
self.source_branch.lock_read():
458
for hook in self.hooks['merge_proposal_body']:
460
'target_branch': self.target_branch_lp.bzr_identity,
461
'modified_files_callback': list_modified_files,
466
def check_proposal(self):
467
"""Check that the submission is sensible."""
468
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
469
raise errors.BzrCommandError(
470
'Source and target branches must be different.')
471
for mp in self.source_branch_lp.landing_targets:
472
if mp.queue_status in ('Merged', 'Rejected'):
474
if mp.target_branch.self_link == self.target_branch_lp.self_link:
475
raise MergeProposalExists(lp_api.canonical_url(mp))
477
def approve_proposal(self, mp):
478
with self.source_branch.lock_read():
482
subject='', # Use the default subject.
483
content=u"Rubberstamp! Proposer approves of own proposal.")
484
_call_webservice(mp.setStatus, status=u'Approved',
485
revid=self.source_branch.last_revision())
487
def create_proposal(self, description, reviewers=None, labels=None,
488
prerequisite_branch=None, commit_message=None):
489
"""Perform the submission."""
491
raise LabelsUnsupported(self)
492
if prerequisite_branch is not None:
493
prereq = self.launchpad.branches.getByUrl(
494
url=prerequisite_branch.user_url)
497
if reviewers is None:
500
mp = _call_webservice(
501
self.source_branch_lp.createMergeProposal,
502
target_branch=self.target_branch_lp,
503
prerequisite_branch=prereq,
504
initial_comment=description.strip(),
505
commit_message=commit_message,
506
reviewers=[self.launchpad.people[reviewer].self_link
507
for reviewer in reviewers],
508
review_types=[None for reviewer in reviewers])
509
except WebserviceFailure as e:
511
if (b'There is already a branch merge proposal '
512
b'registered for branch ') in e.message:
513
raise MergeProposalExists(self.source_branch.user_url)
517
self.approve_proposal(mp)
519
if self.fixes.startswith('lp:'):
520
self.fixes = self.fixes[3:]
523
bug=self.launchpad.bugs[int(self.fixes)])
524
return LaunchpadMergeProposal(mp)
527
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
529
def __init__(self, lp_host, source_branch, target_branch,
530
staging=None, approve=None, fixes=None):
533
:param source_branch: The branch to propose for merging.
534
:param target_branch: The branch to merge into.
535
:param staging: If True, propose the merge against staging instead of
537
:param approve: If True, mark the new proposal as approved immediately.
538
This is useful when a project permits some things to be approved
539
by the submitter (e.g. merges between release and deployment
542
self.lp_host = lp_host
543
self.launchpad = lp_host.launchpad
544
self.source_branch = source_branch
545
(self.source_repo_lp,
546
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
548
if target_branch is None:
549
self.target_branch_lp = self.source_branch.get_target()
550
self.target_branch = _mod_branch.Branch.open(
551
self.target_branch_lp.git_https_url)
553
self.target_branch = target_branch
554
(self.target_repo_lp, self.target_branch_lp) = (
555
self.lp_host._get_lp_git_ref_from_branch(target_branch))
556
self.approve = approve
559
def get_infotext(self):
560
"""Determine the initial comment for the merge proposal."""
561
info = ["Source: %s\n" % self.source_branch.user_url]
562
info.append("Target: %s\n" % self.target_branch.user_url)
565
def get_initial_body(self):
566
"""Get a body for the proposal for the user to modify.
568
:return: a str or None.
570
if not self.hooks['merge_proposal_body']:
573
def list_modified_files():
574
lca_tree = self.source_branch_lp.find_lca_tree(
575
self.target_branch_lp)
576
source_tree = self.source_branch.basis_tree()
577
files = modified_files(lca_tree, source_tree)
579
with self.target_branch.lock_read(), \
580
self.source_branch.lock_read():
582
for hook in self.hooks['merge_proposal_body']:
584
'target_branch': self.target_branch,
585
'modified_files_callback': list_modified_files,
590
def check_proposal(self):
591
"""Check that the submission is sensible."""
592
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
593
raise errors.BzrCommandError(
594
'Source and target branches must be different.')
595
for mp in self.source_branch_lp.landing_targets:
596
if mp.queue_status in ('Merged', 'Rejected'):
598
if mp.target_branch.self_link == self.target_branch_lp.self_link:
599
raise MergeProposalExists(lp_api.canonical_url(mp))
601
def approve_proposal(self, mp):
602
with self.source_branch.lock_read():
606
subject='', # Use the default subject.
607
content=u"Rubberstamp! Proposer approves of own proposal.")
609
mp.setStatus, status=u'Approved',
610
revid=self.source_branch.last_revision())
612
def create_proposal(self, description, reviewers=None, labels=None,
613
prerequisite_branch=None, commit_message=None):
614
"""Perform the submission."""
616
raise LabelsUnsupported(self)
617
if prerequisite_branch is not None:
618
(prereq_repo_lp, prereq_branch_lp) = (
619
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
621
prereq_branch_lp = None
622
if reviewers is None:
625
mp = _call_webservice(
626
self.source_branch_lp.createMergeProposal,
627
merge_target=self.target_branch_lp,
628
merge_prerequisite=prereq_branch_lp,
629
initial_comment=description.strip(),
630
commit_message=commit_message,
632
reviewers=[self.launchpad.people[reviewer].self_link
633
for reviewer in reviewers],
634
review_types=[None for reviewer in reviewers])
635
except WebserviceFailure as e:
637
if ('There is already a branch merge proposal '
638
'registered for branch ') in e.message:
639
raise MergeProposalExists(self.source_branch.user_url)
642
self.approve_proposal(mp)
644
if self.fixes.startswith('lp:'):
645
self.fixes = self.fixes[3:]
648
bug=self.launchpad.bugs[int(self.fixes)])
649
return LaunchpadMergeProposal(mp)
652
def modified_files(old_tree, new_tree):
653
"""Return a list of paths in the new tree with modified contents."""
654
for f, (op, path), c, v, p, n, (ok, k), e in new_tree.iter_changes(
656
if c and k == 'file':