1
# Copyright (C) 2009-2012 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tools for dealing with the Launchpad API."""
19
from __future__ import absolute_import
21
# Importing this module will be expensive, since it imports launchpadlib and
22
# its dependencies. However, our plan is to only load this module when it is
23
# needed by a command that uses it.
29
from urllib.parse import (
33
except ImportError: # python < 3
34
from urlparse import (
47
from ...i18n import gettext
48
from .lp_registration import (
49
InvalidLaunchpadInstance,
54
except ImportError as e:
55
raise errors.DependencyNotPresent('launchpadlib', e)
57
from launchpadlib.launchpad import (
61
from launchpadlib import uris
63
# Declare the minimum version of launchpadlib that we need in order to work.
64
# 1.6.0 is the version of launchpadlib packaged in Ubuntu 10.04, the most
65
# recent Ubuntu LTS release supported on the desktop at the time of writing.
66
MINIMUM_LAUNCHPADLIB_VERSION = (1, 6, 0)
69
def get_cache_directory():
70
"""Return the directory to cache launchpadlib objects in."""
71
return osutils.pathjoin(config.config_dir(), 'launchpad')
74
def parse_launchpadlib_version(version_number):
75
"""Parse a version number of the style used by launchpadlib."""
76
return tuple(map(int, version_number.split('.')))
79
def check_launchpadlib_compatibility():
80
"""Raise an error if launchpadlib has the wrong version number."""
81
installed_version = parse_launchpadlib_version(launchpadlib.__version__)
82
if installed_version < MINIMUM_LAUNCHPADLIB_VERSION:
83
raise errors.DependencyNotPresent(
85
'At least launchpadlib %s is required, but installed version is %s'
86
% (MINIMUM_LAUNCHPADLIB_VERSION, installed_version))
89
def lookup_service_root(service_root):
91
return uris.lookup_service_root(service_root)
93
if service_root != 'qastaging':
95
staging_root = uris.lookup_service_root('staging')
96
return staging_root.replace('staging', 'qastaging')
99
def _get_api_url(service):
100
"""Return the root URL of the Launchpad API.
102
e.g. For the 'staging' Launchpad service, this function returns
103
launchpadlib.launchpad.STAGING_SERVICE_ROOT.
105
:param service: A `LaunchpadService` object.
106
:return: A URL as a string.
108
if service._lp_instance is None:
109
lp_instance = service.DEFAULT_INSTANCE
111
lp_instance = service._lp_instance
113
return lookup_service_root(lp_instance)
115
raise InvalidLaunchpadInstance(lp_instance)
118
class NoLaunchpadBranch(errors.BzrError):
119
_fmt = 'No launchpad branch could be found for branch "%(url)s".'
121
def __init__(self, branch):
122
errors.BzrError.__init__(self, branch=branch, url=branch.base)
125
def login(service, timeout=None, proxy_info=None,
126
version=Launchpad.DEFAULT_VERSION):
127
"""Log in to the Launchpad API.
129
:return: The root `Launchpad` object from launchpadlib.
131
if proxy_info is None:
132
proxy_info = httplib2.proxy_info_from_environment('https')
133
cache_directory = get_cache_directory()
134
launchpad = Launchpad.login_with(
135
'bzr', _get_api_url(service), cache_directory, timeout=timeout,
136
proxy_info=proxy_info, version=version)
137
# XXX: Work-around a minor security bug in launchpadlib < 1.6.3, which
138
# would create this directory with default umask.
139
osutils.chmod_if_possible(cache_directory, 0o700)
143
class LaunchpadBranch(object):
144
"""Provide bzr and lp API access to a Launchpad branch."""
146
def __init__(self, lp_branch, bzr_url, bzr_branch=None, check_update=True):
149
:param lp_branch: The Launchpad branch.
150
:param bzr_url: The URL of the Bazaar branch.
151
:param bzr_branch: An instance of the Bazaar branch.
153
self.bzr_url = bzr_url
154
self._bzr = bzr_branch
155
self._push_bzr = None
156
self._check_update = check_update
161
"""Return the bzr branch for this branch."""
162
if self._bzr is None:
163
self._bzr = branch.Branch.open(self.bzr_url)
168
"""Return the push branch for this branch."""
169
if self._push_bzr is None:
170
self._push_bzr = branch.Branch.open(self.lp.bzr_identity)
171
return self._push_bzr
174
def plausible_launchpad_url(url):
175
"""Is 'url' something that could conceivably be pushed to LP?
177
:param url: A URL that may refer to a Launchpad branch.
182
if url.startswith('lp:'):
184
regex = re.compile('([a-z]*\\+)*(bzr\\+ssh|http)'
185
'://bazaar.*.launchpad.net')
186
return bool(regex.match(url))
189
def candidate_urls(bzr_branch):
190
"""Iterate through related URLs that might be Launchpad URLs.
192
:param bzr_branch: A Bazaar branch to find URLs from.
193
:return: a generator of URL strings.
195
url = bzr_branch.get_public_branch()
198
url = bzr_branch.get_push_location()
201
url = bzr_branch.get_parent()
204
yield bzr_branch.base
207
def tweak_url(url, launchpad):
208
"""Adjust a URL to work with staging, if needed."""
209
if str(launchpad._root_uri) == STAGING_SERVICE_ROOT:
210
return url.replace('bazaar.launchpad.net',
211
'bazaar.staging.launchpad.net')
212
elif str(launchpad._root_uri) == lookup_service_root('qastaging'):
213
return url.replace('bazaar.launchpad.net',
214
'bazaar.qastaging.launchpad.net')
218
def from_bzr(cls, launchpad, bzr_branch, create_missing=True):
219
"""Find a Launchpad branch from a bzr branch."""
221
for url in cls.candidate_urls(bzr_branch):
222
url = cls.tweak_url(url, launchpad)
223
if not cls.plausible_launchpad_url(url):
225
lp_branch = launchpad.branches.getByUrl(url=url)
226
if lp_branch is not None:
229
if not create_missing:
230
raise NoLaunchpadBranch(bzr_branch)
231
lp_branch = cls.create_now(launchpad, bzr_branch)
233
return cls(lp_branch, bzr_branch.base, bzr_branch, check_update)
236
def create_now(cls, launchpad, bzr_branch):
237
"""Create a Bazaar branch on Launchpad for the supplied branch."""
238
url = cls.tweak_url(bzr_branch.get_push_location(), launchpad)
239
if not cls.plausible_launchpad_url(url):
240
raise errors.BzrError(gettext('%s is not registered on Launchpad') %
242
bzr_branch.create_clone_on_transport(transport.get_transport(url))
243
lp_branch = launchpad.branches.getByUrl(url=url)
244
if lp_branch is None:
245
raise errors.BzrError(gettext('%s is not registered on Launchpad') %
249
def get_target(self):
250
"""Return the 'LaunchpadBranch' for the target of this one."""
252
if lp_branch.project is not None:
253
dev_focus = lp_branch.project.development_focus
254
if dev_focus is None:
255
raise errors.BzrError(gettext('%s has no development focus.') %
256
lp_branch.bzr_identity)
257
target = dev_focus.branch
259
raise errors.BzrError(gettext(
260
'development focus %s has no branch.') % dev_focus)
261
elif lp_branch.sourcepackage is not None:
262
target = lp_branch.sourcepackage.getBranch(pocket="Release")
264
raise errors.BzrError(gettext(
265
'source package %s has no branch.') %
266
lp_branch.sourcepackage)
268
raise errors.BzrError(gettext(
269
'%s has no associated product or source package.') %
270
lp_branch.bzr_identity)
271
return LaunchpadBranch(target, target.bzr_identity)
274
"""Update the Launchpad copy of this branch."""
275
if not self._check_update:
277
with self.bzr.lock_read():
278
if self.lp.last_scanned_id is not None:
279
if self.bzr.last_revision() == self.lp.last_scanned_id:
280
trace.note(gettext('%s is already up-to-date.') %
281
self.lp.bzr_identity)
283
graph = self.bzr.repository.get_graph()
284
if not graph.is_ancestor(osutils.safe_utf8(self.lp.last_scanned_id),
285
self.bzr.last_revision()):
286
raise errors.DivergedBranches(self.bzr, self.push_bzr)
287
trace.note(gettext('Pushing to %s') % self.lp.bzr_identity)
288
self.bzr.push(self.push_bzr)
290
def find_lca_tree(self, other):
291
"""Find the revision tree for the LCA of this branch and other.
293
:param other: Another LaunchpadBranch
294
:return: The RevisionTree of the LCA of this branch and other.
296
graph = self.bzr.repository.get_graph(other.bzr.repository)
297
lca = graph.find_unique_lca(self.bzr.last_revision(),
298
other.bzr.last_revision())
299
return self.bzr.repository.revision_tree(lca)
302
def canonical_url(object):
303
"""Return the canonical URL for a branch."""
304
scheme, netloc, path, params, query, fragment = urlparse(
305
str(object.self_link))
306
path = '/'.join(path.split('/')[2:])
307
netloc = netloc.replace('api.', 'code.')
308
return urlunparse((scheme, netloc, path, params, query, fragment))