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
class Launchpad(Hoster):
146
"""The Launchpad hosting service."""
150
# https://bugs.launchpad.net/launchpad/+bug/397676
151
supports_merge_proposal_labels = False
154
self._staging = staging
156
lp_base_url = uris.STAGING_SERVICE_ROOT
158
lp_base_url = uris.LPNET_SERVICE_ROOT
159
self.launchpad = lp_api.connect_launchpad(lp_base_url)
162
return "Launchpad(staging=%s)" % self._staging
164
def hosts(self, branch):
165
# TODO(jelmer): staging vs non-staging?
166
return plausible_launchpad_url(branch.user_url)
169
def probe(cls, branch):
170
if plausible_launchpad_url(branch.user_url):
172
raise UnsupportedHoster(branch)
174
def _get_lp_git_ref_from_branch(self, branch):
175
url, params = urlutils.split_segment_parameters(branch.user_url)
176
(scheme, user, password, host, port, path) = urlutils.parse_url(
178
repo_lp = self.launchpad.git_repositories.getByPath(
179
path=path.strip('/'))
181
ref_path = params['ref']
183
branch_name = params.get('branch', branch.name)
185
ref_path = 'refs/heads/%s' % branch_name
187
ref_path = repo_lp.default_branch
188
ref_lp = repo_lp.getRefByPath(path=ref_path)
189
return (repo_lp, ref_lp)
191
def _get_lp_bzr_branch_from_branch(self, branch):
192
return self.launchpad.branches.getByUrl(
193
url=urlutils.unescape(branch.user_url))
195
def _get_derived_git_path(self, base_path, owner, project):
196
base_repo = self.launchpad.git_repositories.getByPath(path=base_path)
198
project = urlutils.parse_url(base_repo.git_ssh_url)[-1].strip('/')
199
if project.startswith('~'):
200
project = '/'.join(base_path.split('/')[1:])
201
# TODO(jelmer): Surely there is a better way of creating one of these
203
return "~%s/%s" % (owner, project)
205
def _publish_git(self, local_branch, base_path, name, owner, project=None,
206
revision_id=None, overwrite=False, allow_lossy=True):
207
to_path = self._get_derived_git_path(base_path, owner, project)
208
to_transport = get_transport("git+ssh://git.launchpad.net/" + to_path)
210
dir_to = controldir.ControlDir.open_from_transport(to_transport)
211
except errors.NotBranchError:
212
# Didn't find anything
217
br_to = local_branch.create_clone_on_transport(
218
to_transport, revision_id=revision_id, name=name)
219
except errors.NoRoundtrippingSupport:
220
br_to = local_branch.create_clone_on_transport(
221
to_transport, revision_id=revision_id, name=name,
225
dir_to = dir_to.push_branch(
226
local_branch, revision_id, overwrite=overwrite, name=name)
227
except errors.NoRoundtrippingSupport:
230
dir_to = dir_to.push_branch(
231
local_branch, revision_id, overwrite=overwrite, name=name,
233
br_to = dir_to.target_branch
235
"https://git.launchpad.net/%s/+ref/%s" % (to_path, name))
237
def _get_derived_bzr_path(self, base_branch, name, owner, project):
239
base_branch_lp = self._get_lp_bzr_branch_from_branch(base_branch)
240
project = '/'.join(base_branch_lp.unique_name.split('/')[1:-1])
241
# TODO(jelmer): Surely there is a better way of creating one of these
243
return "~%s/%s/%s" % (owner, project, name)
245
def get_push_url(self, branch):
246
(vcs, user, password, path, params) = self._split_url(branch.user_url)
248
branch_lp = self._get_lp_bzr_branch_from_branch(branch)
249
return branch_lp.bzr_identity
251
return urlutils.join_segment_parameters(
252
"git+ssh://git.launchpad.net/" + path, params)
256
def _publish_bzr(self, local_branch, base_branch, name, owner,
257
project=None, revision_id=None, overwrite=False,
259
to_path = self._get_derived_bzr_path(base_branch, name, owner, project)
260
to_transport = get_transport("lp:" + to_path)
262
dir_to = controldir.ControlDir.open_from_transport(to_transport)
263
except errors.NotBranchError:
264
# Didn't find anything
268
br_to = local_branch.create_clone_on_transport(
269
to_transport, revision_id=revision_id)
271
br_to = dir_to.push_branch(
272
local_branch, revision_id, overwrite=overwrite).target_branch
273
return br_to, ("https://code.launchpad.net/" + to_path)
275
def _split_url(self, url):
276
url, params = urlutils.split_segment_parameters(url)
277
(scheme, user, password, host, port, path) = urlutils.parse_url(url)
278
path = path.strip('/')
279
if host.startswith('bazaar.'):
281
elif host.startswith('git.'):
284
raise ValueError("unknown host %s" % host)
285
return (vcs, user, password, path, params)
287
def publish_derived(self, local_branch, base_branch, name, project=None,
288
owner=None, revision_id=None, overwrite=False,
290
"""Publish a branch to the site, derived from base_branch.
292
:param base_branch: branch to derive the new branch from
293
:param new_branch: branch to publish
294
:param name: Name of the new branch on the remote host
295
:param project: Optional project name
296
:param owner: Optional owner
297
:return: resulting branch
300
owner = self.launchpad.me.name
301
(base_vcs, base_user, base_password, base_path,
302
base_params) = self._split_url(base_branch.user_url)
303
# TODO(jelmer): Prevent publishing to development focus
304
if base_vcs == 'bzr':
305
return self._publish_bzr(
306
local_branch, base_branch, name, project=project, owner=owner,
307
revision_id=revision_id, overwrite=overwrite,
308
allow_lossy=allow_lossy)
309
elif base_vcs == 'git':
310
return self._publish_git(
311
local_branch, base_path, name, project=project, owner=owner,
312
revision_id=revision_id, overwrite=overwrite,
313
allow_lossy=allow_lossy)
315
raise AssertionError('not a valid Launchpad URL')
317
def get_derived_branch(self, base_branch, name, project=None, owner=None):
319
owner = self.launchpad.me.name
320
(base_vcs, base_user, base_password, base_path,
321
base_params) = self._split_url(base_branch.user_url)
322
if base_vcs == 'bzr':
323
to_path = self._get_derived_bzr_path(
324
base_branch, name, owner, project)
325
return _mod_branch.Branch.open("lp:" + to_path)
326
elif base_vcs == 'git':
327
to_path = self._get_derived_git_path(
328
base_path.strip('/'), owner, project)
329
to_url = urlutils.join_segment_parameters(
330
"git+ssh://git.launchpad.net/" + to_path,
332
return _mod_branch.Branch.open(to_url)
334
raise AssertionError('not a valid Launchpad URL')
336
def iter_proposals(self, source_branch, target_branch, status='open'):
337
(base_vcs, base_user, base_password, base_path,
338
base_params) = self._split_url(target_branch.user_url)
339
statuses = status_to_lp_mp_statuses(status)
340
if base_vcs == 'bzr':
341
target_branch_lp = self.launchpad.branches.getByUrl(
342
url=target_branch.user_url)
343
source_branch_lp = self.launchpad.branches.getByUrl(
344
url=source_branch.user_url)
345
for mp in target_branch_lp.getMergeProposals(status=statuses):
346
if mp.source_branch_link != source_branch_lp.self_link:
348
yield LaunchpadMergeProposal(mp)
349
elif base_vcs == 'git':
350
(source_repo_lp, source_branch_lp) = (
351
self._get_lp_git_ref_from_branch(source_branch))
352
(target_repo_lp, target_branch_lp) = (
353
self._get_lp_git_ref_from_branch(target_branch))
354
for mp in target_branch_lp.getMergeProposals(status=statuses):
355
if (target_branch_lp.path != mp.target_git_path or
356
target_repo_lp != mp.target_git_repository or
357
source_branch_lp.path != mp.source_git_path or
358
source_repo_lp != mp.source_git_repository):
360
yield LaunchpadMergeProposal(mp)
362
raise AssertionError('not a valid Launchpad URL')
364
def get_proposer(self, source_branch, target_branch):
365
(base_vcs, base_user, base_password, base_path,
366
base_params) = self._split_url(target_branch.user_url)
367
if base_vcs == 'bzr':
368
return LaunchpadBazaarMergeProposalBuilder(
369
self, source_branch, target_branch)
370
elif base_vcs == 'git':
371
return LaunchpadGitMergeProposalBuilder(
372
self, source_branch, target_branch)
374
raise AssertionError('not a valid Launchpad URL')
377
def iter_instances(cls):
380
def iter_my_proposals(self, status='open'):
381
statuses = status_to_lp_mp_statuses(status)
382
for mp in self.launchpad.me.getMergeProposals(status=statuses):
383
yield LaunchpadMergeProposal(mp)
386
class LaunchpadBazaarMergeProposalBuilder(MergeProposalBuilder):
388
def __init__(self, lp_host, source_branch, target_branch, message=None,
389
staging=None, approve=None, fixes=None):
392
:param source_branch: The branch to propose for merging.
393
:param target_branch: The branch to merge into.
394
:param message: The commit message to use. (May be None.)
395
:param staging: If True, propose the merge against staging instead of
397
:param approve: If True, mark the new proposal as approved immediately.
398
This is useful when a project permits some things to be approved
399
by the submitter (e.g. merges between release and deployment
402
self.lp_host = lp_host
403
self.launchpad = lp_host.launchpad
404
self.source_branch = source_branch
405
self.source_branch_lp = self.launchpad.branches.getByUrl(
406
url=source_branch.user_url)
407
if target_branch is None:
408
self.target_branch_lp = self.source_branch_lp.get_target()
409
self.target_branch = _mod_branch.Branch.open(
410
self.target_branch_lp.bzr_identity)
412
self.target_branch = target_branch
413
self.target_branch_lp = self.launchpad.branches.getByUrl(
414
url=target_branch.user_url)
415
self.commit_message = message
416
self.approve = approve
419
def get_infotext(self):
420
"""Determine the initial comment for the merge proposal."""
421
if self.commit_message is not None:
422
return self.commit_message.strip().encode('utf-8')
423
info = ["Source: %s\n" % self.source_branch_lp.bzr_identity]
424
info.append("Target: %s\n" % self.target_branch_lp.bzr_identity)
427
def get_initial_body(self):
428
"""Get a body for the proposal for the user to modify.
430
:return: a str or None.
432
if not self.hooks['merge_proposal_body']:
435
def list_modified_files():
436
lca_tree = self.source_branch_lp.find_lca_tree(
437
self.target_branch_lp)
438
source_tree = self.source_branch.basis_tree()
439
files = modified_files(lca_tree, source_tree)
441
with self.target_branch.lock_read(), \
442
self.source_branch.lock_read():
444
for hook in self.hooks['merge_proposal_body']:
446
'target_branch': self.target_branch_lp.bzr_identity,
447
'modified_files_callback': list_modified_files,
452
def check_proposal(self):
453
"""Check that the submission is sensible."""
454
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
455
raise errors.BzrCommandError(
456
'Source and target branches must be different.')
457
for mp in self.source_branch_lp.landing_targets:
458
if mp.queue_status in ('Merged', 'Rejected'):
460
if mp.target_branch.self_link == self.target_branch_lp.self_link:
461
raise MergeProposalExists(lp_api.canonical_url(mp))
463
def approve_proposal(self, mp):
464
with self.source_branch.lock_read():
468
subject='', # Use the default subject.
469
content=u"Rubberstamp! Proposer approves of own proposal.")
470
_call_webservice(mp.setStatus, status=u'Approved',
471
revid=self.source_branch.last_revision())
473
def create_proposal(self, description, reviewers=None, labels=None,
474
prerequisite_branch=None):
475
"""Perform the submission."""
477
raise LabelsUnsupported()
478
if prerequisite_branch is not None:
479
prereq = self.launchpad.branches.getByUrl(
480
url=prerequisite_branch.user_url)
483
if reviewers is None:
486
mp = _call_webservice(
487
self.source_branch_lp.createMergeProposal,
488
target_branch=self.target_branch_lp,
489
prerequisite_branch=prereq,
490
initial_comment=description.strip(),
491
commit_message=self.commit_message,
492
reviewers=[self.launchpad.people[reviewer].self_link
493
for reviewer in reviewers],
494
review_types=[None for reviewer in reviewers])
495
except WebserviceFailure as e:
497
if (b'There is already a branch merge proposal '
498
b'registered for branch ') in e.message:
499
raise MergeProposalExists(self.source_branch.user_url)
503
self.approve_proposal(mp)
505
if self.fixes.startswith('lp:'):
506
self.fixes = self.fixes[3:]
509
bug=self.launchpad.bugs[int(self.fixes)])
510
return LaunchpadMergeProposal(mp)
513
class LaunchpadGitMergeProposalBuilder(MergeProposalBuilder):
515
def __init__(self, lp_host, source_branch, target_branch, message=None,
516
staging=None, approve=None, fixes=None):
519
:param source_branch: The branch to propose for merging.
520
:param target_branch: The branch to merge into.
521
:param message: The commit message to use. (May be None.)
522
:param staging: If True, propose the merge against staging instead of
524
:param approve: If True, mark the new proposal as approved immediately.
525
This is useful when a project permits some things to be approved
526
by the submitter (e.g. merges between release and deployment
529
self.lp_host = lp_host
530
self.launchpad = lp_host.launchpad
531
self.source_branch = source_branch
532
(self.source_repo_lp,
533
self.source_branch_lp) = self.lp_host._get_lp_git_ref_from_branch(
535
if target_branch is None:
536
self.target_branch_lp = self.source_branch.get_target()
537
self.target_branch = _mod_branch.Branch.open(
538
self.target_branch_lp.git_https_url)
540
self.target_branch = target_branch
541
(self.target_repo_lp, self.target_branch_lp) = (
542
self.lp_host._get_lp_git_ref_from_branch(target_branch))
543
self.commit_message = message
544
self.approve = approve
547
def get_infotext(self):
548
"""Determine the initial comment for the merge proposal."""
549
if self.commit_message is not None:
550
return self.commit_message.strip().encode('utf-8')
551
info = ["Source: %s\n" % self.source_branch.user_url]
552
info.append("Target: %s\n" % self.target_branch.user_url)
555
def get_initial_body(self):
556
"""Get a body for the proposal for the user to modify.
558
:return: a str or None.
560
if not self.hooks['merge_proposal_body']:
563
def list_modified_files():
564
lca_tree = self.source_branch_lp.find_lca_tree(
565
self.target_branch_lp)
566
source_tree = self.source_branch.basis_tree()
567
files = modified_files(lca_tree, source_tree)
569
with self.target_branch.lock_read(), \
570
self.source_branch.lock_read():
572
for hook in self.hooks['merge_proposal_body']:
574
'target_branch': self.target_branch,
575
'modified_files_callback': list_modified_files,
580
def check_proposal(self):
581
"""Check that the submission is sensible."""
582
if self.source_branch_lp.self_link == self.target_branch_lp.self_link:
583
raise errors.BzrCommandError(
584
'Source and target branches must be different.')
585
for mp in self.source_branch_lp.landing_targets:
586
if mp.queue_status in ('Merged', 'Rejected'):
588
if mp.target_branch.self_link == self.target_branch_lp.self_link:
589
raise MergeProposalExists(lp_api.canonical_url(mp))
591
def approve_proposal(self, mp):
592
with self.source_branch.lock_read():
596
subject='', # Use the default subject.
597
content=u"Rubberstamp! Proposer approves of own proposal.")
599
mp.setStatus, status=u'Approved',
600
revid=self.source_branch.last_revision())
602
def create_proposal(self, description, reviewers=None, labels=None,
603
prerequisite_branch=None):
604
"""Perform the submission."""
606
raise LabelsUnsupported()
607
if prerequisite_branch is not None:
608
(prereq_repo_lp, prereq_branch_lp) = (
609
self.lp_host._get_lp_git_ref_from_branch(prerequisite_branch))
611
prereq_branch_lp = None
612
if reviewers is None:
615
mp = _call_webservice(
616
self.source_branch_lp.createMergeProposal,
617
merge_target=self.target_branch_lp,
618
merge_prerequisite=prereq_branch_lp,
619
initial_comment=description.strip(),
620
commit_message=self.commit_message,
622
reviewers=[self.launchpad.people[reviewer].self_link
623
for reviewer in reviewers],
624
review_types=[None for reviewer in reviewers])
625
except WebserviceFailure as e:
627
if ('There is already a branch merge proposal '
628
'registered for branch ') in e.message:
629
raise MergeProposalExists(self.source_branch.user_url)
632
self.approve_proposal(mp)
634
if self.fixes.startswith('lp:'):
635
self.fixes = self.fixes[3:]
638
bug=self.launchpad.bugs[int(self.fixes)])
639
return LaunchpadMergeProposal(mp)
642
def modified_files(old_tree, new_tree):
643
"""Return a list of paths in the new tree with modified contents."""
644
for f, (op, path), c, v, p, n, (ok, k), e in new_tree.iter_changes(
646
if c and k == 'file':