/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 brzlib/plugins/launchpad/lp_api.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

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
 
from ... import (
 
31
from brzlib import (
31
32
    branch,
32
 
    bedding,
 
33
    config,
33
34
    errors,
34
35
    osutils,
35
36
    trace,
36
37
    transport,
37
38
    )
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)
 
39
from brzlib.i18n import gettext
 
40
from brzlib.plugins.launchpad.lp_registration import (
 
41
    InvalidLaunchpadInstance,
 
42
    )
49
43
 
50
44
try:
51
45
    import launchpadlib
52
 
except ImportError as e:
53
 
    raise LaunchpadlibMissing(e)
 
46
except ImportError, e:
 
47
    raise errors.DependencyNotPresent('launchpadlib', e)
54
48
 
55
49
from launchpadlib.launchpad import (
 
50
    STAGING_SERVICE_ROOT,
56
51
    Launchpad,
57
52
    )
58
53
from launchpadlib import uris
59
54
 
60
55
# Declare the minimum version of launchpadlib that we need in order to work.
61
 
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)
62
59
 
63
60
 
64
61
def get_cache_directory():
65
62
    """Return the directory to cache launchpadlib objects in."""
66
 
    return osutils.pathjoin(bedding.cache_dir(), 'launchpad')
 
63
    return osutils.pathjoin(config.config_dir(), 'launchpad')
67
64
 
68
65
 
69
66
def parse_launchpadlib_version(version_number):
75
72
    """Raise an error if launchpadlib has the wrong version number."""
76
73
    installed_version = parse_launchpadlib_version(launchpadlib.__version__)
77
74
    if installed_version < MINIMUM_LAUNCHPADLIB_VERSION:
78
 
        raise errors.DependencyNotPresent(
79
 
            'launchpadlib',
80
 
            'At least launchpadlib %s is required, but installed version is %s'
81
 
            % (MINIMUM_LAUNCHPADLIB_VERSION, installed_version))
 
75
        raise errors.IncompatibleAPI(
 
76
            'launchpadlib', MINIMUM_LAUNCHPADLIB_VERSION,
 
77
            installed_version, installed_version)
82
78
 
83
79
 
84
80
def lookup_service_root(service_root):
91
87
        return staging_root.replace('staging', 'qastaging')
92
88
 
93
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
 
94
109
class NoLaunchpadBranch(errors.BzrError):
95
110
    _fmt = 'No launchpad branch could be found for branch "%(url)s".'
96
111
 
98
113
        errors.BzrError.__init__(self, branch=branch, url=branch.base)
99
114
 
100
115
 
101
 
def connect_launchpad(base_url, timeout=None, proxy_info=None,
102
 
                      version=Launchpad.DEFAULT_VERSION):
 
116
def login(service, timeout=None, proxy_info=None,
 
117
          version=Launchpad.DEFAULT_VERSION):
103
118
    """Log in to the Launchpad API.
104
119
 
105
120
    :return: The root `Launchpad` object from launchpadlib.
106
121
    """
107
122
    if proxy_info is None:
108
 
        import httplib2
109
123
        proxy_info = httplib2.proxy_info_from_environment('https')
110
 
    try:
111
 
        cache_directory = get_cache_directory()
112
 
    except EnvironmentError:
113
 
        cache_directory = None
114
 
    return Launchpad.login_with(
115
 
        'breezy', base_url, cache_directory, timeout=timeout,
 
124
    cache_directory = get_cache_directory()
 
125
    launchpad = Launchpad.login_with(
 
126
        'bzr', _get_api_url(service), cache_directory, timeout=timeout,
116
127
        proxy_info=proxy_info, version=version)
117
 
 
 
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
118
132
 
119
133
 
120
134
class LaunchpadBranch(object):
158
172
            return False
159
173
        if url.startswith('lp:'):
160
174
            return True
161
 
        regex = re.compile('([a-z]*\\+)*(bzr\\+ssh|http)'
 
175
        regex = re.compile('([a-z]*\+)*(bzr\+ssh|http)'
162
176
                           '://bazaar.*.launchpad.net')
163
177
        return bool(regex.match(url))
164
178
 
183
197
    @staticmethod
184
198
    def tweak_url(url, launchpad):
185
199
        """Adjust a URL to work with staging, if needed."""
186
 
        if str(launchpad._root_uri) == uris.STAGING_SERVICE_ROOT:
 
200
        if str(launchpad._root_uri) == STAGING_SERVICE_ROOT:
187
201
            return url.replace('bazaar.launchpad.net',
188
202
                               'bazaar.staging.launchpad.net')
189
203
        elif str(launchpad._root_uri) == lookup_service_root('qastaging'):
220
234
        lp_branch = launchpad.branches.getByUrl(url=url)
221
235
        if lp_branch is None:
222
236
            raise errors.BzrError(gettext('%s is not registered on Launchpad') %
223
 
                                  url)
 
237
                                                                            url)
224
238
        return lp_branch
225
239
 
226
240
    def get_target(self):
230
244
            dev_focus = lp_branch.project.development_focus
231
245
            if dev_focus is None:
232
246
                raise errors.BzrError(gettext('%s has no development focus.') %
233
 
                                      lp_branch.bzr_identity)
 
247
                                  lp_branch.bzr_identity)
234
248
            target = dev_focus.branch
235
249
            if target is None:
236
250
                raise errors.BzrError(gettext(
237
 
                    'development focus %s has no branch.') % dev_focus)
 
251
                        'development focus %s has no branch.') % dev_focus)
238
252
        elif lp_branch.sourcepackage is not None:
239
253
            target = lp_branch.sourcepackage.getBranch(pocket="Release")
240
254
            if target is None:
243
257
                                      lp_branch.sourcepackage)
244
258
        else:
245
259
            raise errors.BzrError(gettext(
246
 
                '%s has no associated product or source package.') %
247
 
                lp_branch.bzr_identity)
 
260
                        '%s has no associated product or source package.') %
 
261
                                  lp_branch.bzr_identity)
248
262
        return LaunchpadBranch(target, target.bzr_identity)
249
263
 
250
264
    def update_lp(self):
251
265
        """Update the Launchpad copy of this branch."""
252
266
        if not self._check_update:
253
267
            return
254
 
        with self.bzr.lock_read():
 
268
        self.bzr.lock_read()
 
269
        try:
255
270
            if self.lp.last_scanned_id is not None:
256
271
                if self.bzr.last_revision() == self.lp.last_scanned_id:
257
272
                    trace.note(gettext('%s is already up-to-date.') %
258
273
                               self.lp.bzr_identity)
259
274
                    return
260
275
                graph = self.bzr.repository.get_graph()
261
 
                if not graph.is_ancestor(osutils.safe_utf8(self.lp.last_scanned_id),
 
276
                if not graph.is_ancestor(self.lp.last_scanned_id,
262
277
                                         self.bzr.last_revision()):
263
278
                    raise errors.DivergedBranches(self.bzr, self.push_bzr)
264
279
                trace.note(gettext('Pushing to %s') % self.lp.bzr_identity)
265
280
            self.bzr.push(self.push_bzr)
 
281
        finally:
 
282
            self.bzr.unlock()
266
283
 
267
284
    def find_lca_tree(self, other):
268
285
        """Find the revision tree for the LCA of this branch and other.
278
295
 
279
296
def canonical_url(object):
280
297
    """Return the canonical URL for a branch."""
281
 
    scheme, netloc, path, params, query, fragment = urlparse(
 
298
    scheme, netloc, path, params, query, fragment = urlparse.urlparse(
282
299
        str(object.self_link))
283
300
    path = '/'.join(path.split('/')[2:])
284
301
    netloc = netloc.replace('api.', 'code.')
285
 
    return urlunparse((scheme, netloc, path, params, query, fragment))
 
302
    return urlparse.urlunparse((scheme, netloc, path, params, query,
 
303
                                fragment))