/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: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

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