/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/plugins/launchpad/lp_api.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-08 23:30:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170608233031-3qavls2o7a1pqllj
Update imports.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Tools for dealing with the Launchpad API."""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
# Importing this module will be expensive, since it imports launchpadlib and
20
22
# its dependencies. However, our plan is to only load this module when it is
21
23
# needed by a command that uses it.
22
24
 
23
25
 
 
26
import httplib2
 
27
import os
24
28
import re
25
 
from urllib.parse import (
26
 
    urlparse,
27
 
    urlunparse,
28
 
    )
 
29
import urlparse
29
30
 
30
31
from ... import (
31
32
    branch,
32
 
    bedding,
 
33
    config,
33
34
    errors,
34
35
    osutils,
35
36
    trace,
36
37
    transport,
37
38
    )
38
39
from ...i18n import gettext
39
 
 
40
 
 
41
 
class LaunchpadlibMissing(errors.DependencyNotPresent):
42
 
 
43
 
    _fmt = ("launchpadlib is required for Launchpad API access. "
44
 
            "Please install the launchpadlib package.")
45
 
 
46
 
    def __init__(self, e):
47
 
        super(LaunchpadlibMissing, self).__init__(
48
 
            'launchpadlib', e)
 
40
from .lp_registration import (
 
41
    InvalidLaunchpadInstance,
 
42
    )
49
43
 
50
44
try:
51
45
    import launchpadlib
52
46
except ImportError as e:
53
 
    raise LaunchpadlibMissing(e)
 
47
    raise errors.DependencyNotPresent('launchpadlib', e)
54
48
 
55
 
from launchpadlib.credentials import RequestTokenAuthorizationEngine
56
49
from launchpadlib.launchpad import (
 
50
    STAGING_SERVICE_ROOT,
57
51
    Launchpad,
58
52
    )
59
53
from launchpadlib import uris
60
54
 
61
55
# Declare the minimum version of launchpadlib that we need in order to work.
62
 
MINIMUM_LAUNCHPADLIB_VERSION = (1, 6, 3)
 
56
# 1.6.0 is the version of launchpadlib packaged in Ubuntu 10.04, the most
 
57
# recent Ubuntu LTS release supported on the desktop at the time of writing.
 
58
MINIMUM_LAUNCHPADLIB_VERSION = (1, 6, 0)
63
59
 
64
60
 
65
61
def get_cache_directory():
66
62
    """Return the directory to cache launchpadlib objects in."""
67
 
    return osutils.pathjoin(bedding.cache_dir(), 'launchpad')
 
63
    return osutils.pathjoin(config.config_dir(), 'launchpad')
68
64
 
69
65
 
70
66
def parse_launchpadlib_version(version_number):
76
72
    """Raise an error if launchpadlib has the wrong version number."""
77
73
    installed_version = parse_launchpadlib_version(launchpadlib.__version__)
78
74
    if installed_version < MINIMUM_LAUNCHPADLIB_VERSION:
79
 
        raise errors.DependencyNotPresent(
80
 
            'launchpadlib',
81
 
            'At least launchpadlib %s is required, but installed version is %s'
82
 
            % (MINIMUM_LAUNCHPADLIB_VERSION, installed_version))
 
75
        raise errors.IncompatibleAPI(
 
76
            'launchpadlib', MINIMUM_LAUNCHPADLIB_VERSION,
 
77
            installed_version, installed_version)
83
78
 
84
79
 
85
80
def lookup_service_root(service_root):
92
87
        return staging_root.replace('staging', 'qastaging')
93
88
 
94
89
 
 
90
def _get_api_url(service):
 
91
    """Return the root URL of the Launchpad API.
 
92
 
 
93
    e.g. For the 'staging' Launchpad service, this function returns
 
94
    launchpadlib.launchpad.STAGING_SERVICE_ROOT.
 
95
 
 
96
    :param service: A `LaunchpadService` object.
 
97
    :return: A URL as a string.
 
98
    """
 
99
    if service._lp_instance is None:
 
100
        lp_instance = service.DEFAULT_INSTANCE
 
101
    else:
 
102
        lp_instance = service._lp_instance
 
103
    try:
 
104
        return lookup_service_root(lp_instance)
 
105
    except ValueError:
 
106
        raise InvalidLaunchpadInstance(lp_instance)
 
107
 
 
108
 
95
109
class NoLaunchpadBranch(errors.BzrError):
96
110
    _fmt = 'No launchpad branch could be found for branch "%(url)s".'
97
111
 
99
113
        errors.BzrError.__init__(self, branch=branch, url=branch.base)
100
114
 
101
115
 
102
 
def get_auth_engine(base_url):
103
 
    return Launchpad.authorization_engine_factory(base_url, 'breezy')
104
 
 
105
 
 
106
 
def get_credential_store():
107
 
    return Launchpad.credential_store_factory(None)
108
 
 
109
 
 
110
 
def connect_launchpad(base_url, timeout=None, proxy_info=None,
111
 
                      version=Launchpad.DEFAULT_VERSION):
 
116
def login(service, timeout=None, proxy_info=None,
 
117
          version=Launchpad.DEFAULT_VERSION):
112
118
    """Log in to the Launchpad API.
113
119
 
114
120
    :return: The root `Launchpad` object from launchpadlib.
115
121
    """
116
122
    if proxy_info is None:
117
 
        import httplib2
118
123
        proxy_info = httplib2.proxy_info_from_environment('https')
119
 
    try:
120
 
        cache_directory = get_cache_directory()
121
 
    except EnvironmentError:
122
 
        cache_directory = None
123
 
    credential_store = get_credential_store()
124
 
    authorization_engine = get_auth_engine(base_url)
125
 
    return Launchpad.login_with(
126
 
        'breezy', base_url, cache_directory, timeout=timeout,
127
 
        credential_store=credential_store,
128
 
        authorization_engine=authorization_engine,
 
124
    cache_directory = get_cache_directory()
 
125
    launchpad = Launchpad.login_with(
 
126
        'bzr', _get_api_url(service), cache_directory, timeout=timeout,
129
127
        proxy_info=proxy_info, version=version)
130
 
 
 
128
    # XXX: Work-around a minor security bug in launchpadlib < 1.6.3, which
 
129
    # would create this directory with default umask.
 
130
    osutils.chmod_if_possible(cache_directory, 0o700)
 
131
    return launchpad
131
132
 
132
133
 
133
134
class LaunchpadBranch(object):
171
172
            return False
172
173
        if url.startswith('lp:'):
173
174
            return True
174
 
        regex = re.compile('([a-z]*\\+)*(bzr\\+ssh|http)'
 
175
        regex = re.compile('([a-z]*\+)*(bzr\+ssh|http)'
175
176
                           '://bazaar.*.launchpad.net')
176
177
        return bool(regex.match(url))
177
178
 
196
197
    @staticmethod
197
198
    def tweak_url(url, launchpad):
198
199
        """Adjust a URL to work with staging, if needed."""
199
 
        if str(launchpad._root_uri) == uris.STAGING_SERVICE_ROOT:
 
200
        if str(launchpad._root_uri) == STAGING_SERVICE_ROOT:
200
201
            return url.replace('bazaar.launchpad.net',
201
202
                               'bazaar.staging.launchpad.net')
202
203
        elif str(launchpad._root_uri) == lookup_service_root('qastaging'):
233
234
        lp_branch = launchpad.branches.getByUrl(url=url)
234
235
        if lp_branch is None:
235
236
            raise errors.BzrError(gettext('%s is not registered on Launchpad') %
236
 
                                  url)
 
237
                                                                            url)
237
238
        return lp_branch
238
239
 
239
240
    def get_target(self):
243
244
            dev_focus = lp_branch.project.development_focus
244
245
            if dev_focus is None:
245
246
                raise errors.BzrError(gettext('%s has no development focus.') %
246
 
                                      lp_branch.bzr_identity)
 
247
                                  lp_branch.bzr_identity)
247
248
            target = dev_focus.branch
248
249
            if target is None:
249
250
                raise errors.BzrError(gettext(
250
 
                    'development focus %s has no branch.') % dev_focus)
 
251
                        'development focus %s has no branch.') % dev_focus)
251
252
        elif lp_branch.sourcepackage is not None:
252
253
            target = lp_branch.sourcepackage.getBranch(pocket="Release")
253
254
            if target is None:
256
257
                                      lp_branch.sourcepackage)
257
258
        else:
258
259
            raise errors.BzrError(gettext(
259
 
                '%s has no associated product or source package.') %
260
 
                lp_branch.bzr_identity)
 
260
                        '%s has no associated product or source package.') %
 
261
                                  lp_branch.bzr_identity)
261
262
        return LaunchpadBranch(target, target.bzr_identity)
262
263
 
263
264
    def update_lp(self):
264
265
        """Update the Launchpad copy of this branch."""
265
266
        if not self._check_update:
266
267
            return
267
 
        with self.bzr.lock_read():
 
268
        self.bzr.lock_read()
 
269
        try:
268
270
            if self.lp.last_scanned_id is not None:
269
271
                if self.bzr.last_revision() == self.lp.last_scanned_id:
270
272
                    trace.note(gettext('%s is already up-to-date.') %
271
273
                               self.lp.bzr_identity)
272
274
                    return
273
275
                graph = self.bzr.repository.get_graph()
274
 
                if not graph.is_ancestor(osutils.safe_utf8(self.lp.last_scanned_id),
 
276
                if not graph.is_ancestor(self.lp.last_scanned_id,
275
277
                                         self.bzr.last_revision()):
276
278
                    raise errors.DivergedBranches(self.bzr, self.push_bzr)
277
279
                trace.note(gettext('Pushing to %s') % self.lp.bzr_identity)
278
280
            self.bzr.push(self.push_bzr)
 
281
        finally:
 
282
            self.bzr.unlock()
279
283
 
280
284
    def find_lca_tree(self, other):
281
285
        """Find the revision tree for the LCA of this branch and other.
291
295
 
292
296
def canonical_url(object):
293
297
    """Return the canonical URL for a branch."""
294
 
    scheme, netloc, path, params, query, fragment = urlparse(
 
298
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(
295
299
        str(object.self_link))
296
300
    path = '/'.join(path.split('/')[2:])
297
301
    netloc = netloc.replace('api.', 'code.')
298
 
    return urlunparse((scheme, netloc, path, params, query, fragment))
 
302
    return urlparse.urlunparse((scheme, netloc, path, params, query,
 
303
                                fragment))