/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-07-23 22:06:41 UTC
  • mfrom: (6738 trunk)
  • mto: This revision was merged to the branch mainline in revision 6739.
  • Revision ID: jelmer@jelmer.uk-20170723220641-69eczax9bmv8d6kk
Merge trunk, address review comments.

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):
92
88
        return staging_root.replace('staging', 'qastaging')
93
89
 
94
90
 
 
91
def _get_api_url(service):
 
92
    """Return the root URL of the Launchpad API.
 
93
 
 
94
    e.g. For the 'staging' Launchpad service, this function returns
 
95
    launchpadlib.launchpad.STAGING_SERVICE_ROOT.
 
96
 
 
97
    :param service: A `LaunchpadService` object.
 
98
    :return: A URL as a string.
 
99
    """
 
100
    if service._lp_instance is None:
 
101
        lp_instance = service.DEFAULT_INSTANCE
 
102
    else:
 
103
        lp_instance = service._lp_instance
 
104
    try:
 
105
        return lookup_service_root(lp_instance)
 
106
    except ValueError:
 
107
        raise InvalidLaunchpadInstance(lp_instance)
 
108
 
 
109
 
95
110
class NoLaunchpadBranch(errors.BzrError):
96
111
    _fmt = 'No launchpad branch could be found for branch "%(url)s".'
97
112
 
99
114
        errors.BzrError.__init__(self, branch=branch, url=branch.base)
100
115
 
101
116
 
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):
 
117
def login(service, timeout=None, proxy_info=None,
 
118
          version=Launchpad.DEFAULT_VERSION):
112
119
    """Log in to the Launchpad API.
113
120
 
114
121
    :return: The root `Launchpad` object from launchpadlib.
115
122
    """
116
123
    if proxy_info is None:
117
 
        import httplib2
118
124
        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,
 
125
    cache_directory = get_cache_directory()
 
126
    launchpad = Launchpad.login_with(
 
127
        'bzr', _get_api_url(service), cache_directory, timeout=timeout,
129
128
        proxy_info=proxy_info, version=version)
130
 
 
 
129
    # XXX: Work-around a minor security bug in launchpadlib < 1.6.3, which
 
130
    # would create this directory with default umask.
 
131
    osutils.chmod_if_possible(cache_directory, 0o700)
 
132
    return launchpad
131
133
 
132
134
 
133
135
class LaunchpadBranch(object):
171
173
            return False
172
174
        if url.startswith('lp:'):
173
175
            return True
174
 
        regex = re.compile('([a-z]*\\+)*(bzr\\+ssh|http)'
 
176
        regex = re.compile('([a-z]*\+)*(bzr\+ssh|http)'
175
177
                           '://bazaar.*.launchpad.net')
176
178
        return bool(regex.match(url))
177
179
 
196
198
    @staticmethod
197
199
    def tweak_url(url, launchpad):
198
200
        """Adjust a URL to work with staging, if needed."""
199
 
        if str(launchpad._root_uri) == uris.STAGING_SERVICE_ROOT:
 
201
        if str(launchpad._root_uri) == STAGING_SERVICE_ROOT:
200
202
            return url.replace('bazaar.launchpad.net',
201
203
                               'bazaar.staging.launchpad.net')
202
204
        elif str(launchpad._root_uri) == lookup_service_root('qastaging'):
233
235
        lp_branch = launchpad.branches.getByUrl(url=url)
234
236
        if lp_branch is None:
235
237
            raise errors.BzrError(gettext('%s is not registered on Launchpad') %
236
 
                                  url)
 
238
                                                                            url)
237
239
        return lp_branch
238
240
 
239
241
    def get_target(self):
243
245
            dev_focus = lp_branch.project.development_focus
244
246
            if dev_focus is None:
245
247
                raise errors.BzrError(gettext('%s has no development focus.') %
246
 
                                      lp_branch.bzr_identity)
 
248
                                  lp_branch.bzr_identity)
247
249
            target = dev_focus.branch
248
250
            if target is None:
249
251
                raise errors.BzrError(gettext(
250
 
                    'development focus %s has no branch.') % dev_focus)
 
252
                        'development focus %s has no branch.') % dev_focus)
251
253
        elif lp_branch.sourcepackage is not None:
252
254
            target = lp_branch.sourcepackage.getBranch(pocket="Release")
253
255
            if target is None:
256
258
                                      lp_branch.sourcepackage)
257
259
        else:
258
260
            raise errors.BzrError(gettext(
259
 
                '%s has no associated product or source package.') %
260
 
                lp_branch.bzr_identity)
 
261
                        '%s has no associated product or source package.') %
 
262
                                  lp_branch.bzr_identity)
261
263
        return LaunchpadBranch(target, target.bzr_identity)
262
264
 
263
265
    def update_lp(self):
264
266
        """Update the Launchpad copy of this branch."""
265
267
        if not self._check_update:
266
268
            return
267
 
        with self.bzr.lock_read():
 
269
        self.bzr.lock_read()
 
270
        try:
268
271
            if self.lp.last_scanned_id is not None:
269
272
                if self.bzr.last_revision() == self.lp.last_scanned_id:
270
273
                    trace.note(gettext('%s is already up-to-date.') %
271
274
                               self.lp.bzr_identity)
272
275
                    return
273
276
                graph = self.bzr.repository.get_graph()
274
 
                if not graph.is_ancestor(osutils.safe_utf8(self.lp.last_scanned_id),
 
277
                if not graph.is_ancestor(self.lp.last_scanned_id,
275
278
                                         self.bzr.last_revision()):
276
279
                    raise errors.DivergedBranches(self.bzr, self.push_bzr)
277
280
                trace.note(gettext('Pushing to %s') % self.lp.bzr_identity)
278
281
            self.bzr.push(self.push_bzr)
 
282
        finally:
 
283
            self.bzr.unlock()
279
284
 
280
285
    def find_lca_tree(self, other):
281
286
        """Find the revision tree for the LCA of this branch and other.
291
296
 
292
297
def canonical_url(object):
293
298
    """Return the canonical URL for a branch."""
294
 
    scheme, netloc, path, params, query, fragment = urlparse(
 
299
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(
295
300
        str(object.self_link))
296
301
    path = '/'.join(path.split('/')[2:])
297
302
    netloc = netloc.replace('api.', 'code.')
298
 
    return urlunparse((scheme, netloc, path, params, query, fragment))
 
303
    return urlparse.urlunparse((scheme, netloc, path, params, query,
 
304
                                fragment))