/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: 2020-05-06 02:13:25 UTC
  • mfrom: (7490.7.21 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200506021325-awbmmqu1zyorz7sj
Merge 3.1 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009-2012 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Tools for dealing with the Launchpad API."""
 
18
 
 
19
# Importing this module will be expensive, since it imports launchpadlib and
 
20
# its dependencies. However, our plan is to only load this module when it is
 
21
# needed by a command that uses it.
 
22
 
 
23
 
 
24
import re
 
25
from urllib.parse import (
 
26
    urlparse,
 
27
    urlunparse,
 
28
    )
 
29
 
 
30
from ... import (
 
31
    branch,
 
32
    bedding,
 
33
    errors,
 
34
    osutils,
 
35
    trace,
 
36
    transport,
 
37
    )
 
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)
 
49
 
 
50
try:
 
51
    import launchpadlib
 
52
except ImportError as e:
 
53
    raise LaunchpadlibMissing(e)
 
54
 
 
55
from launchpadlib.launchpad import (
 
56
    Launchpad,
 
57
    )
 
58
from launchpadlib import uris
 
59
 
 
60
# Declare the minimum version of launchpadlib that we need in order to work.
 
61
MINIMUM_LAUNCHPADLIB_VERSION = (1, 6, 3)
 
62
 
 
63
 
 
64
def get_cache_directory():
 
65
    """Return the directory to cache launchpadlib objects in."""
 
66
    return osutils.pathjoin(bedding.cache_dir(), 'launchpad')
 
67
 
 
68
 
 
69
def parse_launchpadlib_version(version_number):
 
70
    """Parse a version number of the style used by launchpadlib."""
 
71
    return tuple(map(int, version_number.split('.')))
 
72
 
 
73
 
 
74
def check_launchpadlib_compatibility():
 
75
    """Raise an error if launchpadlib has the wrong version number."""
 
76
    installed_version = parse_launchpadlib_version(launchpadlib.__version__)
 
77
    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))
 
82
 
 
83
 
 
84
def lookup_service_root(service_root):
 
85
    try:
 
86
        return uris.lookup_service_root(service_root)
 
87
    except ValueError:
 
88
        if service_root != 'qastaging':
 
89
            raise
 
90
        staging_root = uris.lookup_service_root('staging')
 
91
        return staging_root.replace('staging', 'qastaging')
 
92
 
 
93
 
 
94
class NoLaunchpadBranch(errors.BzrError):
 
95
    _fmt = 'No launchpad branch could be found for branch "%(url)s".'
 
96
 
 
97
    def __init__(self, branch):
 
98
        errors.BzrError.__init__(self, branch=branch, url=branch.base)
 
99
 
 
100
 
 
101
def connect_launchpad(base_url, timeout=None, proxy_info=None,
 
102
                      version=Launchpad.DEFAULT_VERSION):
 
103
    """Log in to the Launchpad API.
 
104
 
 
105
    :return: The root `Launchpad` object from launchpadlib.
 
106
    """
 
107
    if proxy_info is None:
 
108
        import httplib2
 
109
        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,
 
116
        proxy_info=proxy_info, version=version)
 
117
 
 
118
 
 
119
 
 
120
class LaunchpadBranch(object):
 
121
    """Provide bzr and lp API access to a Launchpad branch."""
 
122
 
 
123
    def __init__(self, lp_branch, bzr_url, bzr_branch=None, check_update=True):
 
124
        """Constructor.
 
125
 
 
126
        :param lp_branch: The Launchpad branch.
 
127
        :param bzr_url: The URL of the Bazaar branch.
 
128
        :param bzr_branch: An instance of the Bazaar branch.
 
129
        """
 
130
        self.bzr_url = bzr_url
 
131
        self._bzr = bzr_branch
 
132
        self._push_bzr = None
 
133
        self._check_update = check_update
 
134
        self.lp = lp_branch
 
135
 
 
136
    @property
 
137
    def bzr(self):
 
138
        """Return the bzr branch for this branch."""
 
139
        if self._bzr is None:
 
140
            self._bzr = branch.Branch.open(self.bzr_url)
 
141
        return self._bzr
 
142
 
 
143
    @property
 
144
    def push_bzr(self):
 
145
        """Return the push branch for this branch."""
 
146
        if self._push_bzr is None:
 
147
            self._push_bzr = branch.Branch.open(self.lp.bzr_identity)
 
148
        return self._push_bzr
 
149
 
 
150
    @staticmethod
 
151
    def plausible_launchpad_url(url):
 
152
        """Is 'url' something that could conceivably be pushed to LP?
 
153
 
 
154
        :param url: A URL that may refer to a Launchpad branch.
 
155
        :return: A boolean.
 
156
        """
 
157
        if url is None:
 
158
            return False
 
159
        if url.startswith('lp:'):
 
160
            return True
 
161
        regex = re.compile('([a-z]*\\+)*(bzr\\+ssh|http)'
 
162
                           '://bazaar.*.launchpad.net')
 
163
        return bool(regex.match(url))
 
164
 
 
165
    @staticmethod
 
166
    def candidate_urls(bzr_branch):
 
167
        """Iterate through related URLs that might be Launchpad URLs.
 
168
 
 
169
        :param bzr_branch: A Bazaar branch to find URLs from.
 
170
        :return: a generator of URL strings.
 
171
        """
 
172
        url = bzr_branch.get_public_branch()
 
173
        if url is not None:
 
174
            yield url
 
175
        url = bzr_branch.get_push_location()
 
176
        if url is not None:
 
177
            yield url
 
178
        url = bzr_branch.get_parent()
 
179
        if url is not None:
 
180
            yield url
 
181
        yield bzr_branch.base
 
182
 
 
183
    @staticmethod
 
184
    def tweak_url(url, launchpad):
 
185
        """Adjust a URL to work with staging, if needed."""
 
186
        if str(launchpad._root_uri) == uris.STAGING_SERVICE_ROOT:
 
187
            return url.replace('bazaar.launchpad.net',
 
188
                               'bazaar.staging.launchpad.net')
 
189
        elif str(launchpad._root_uri) == lookup_service_root('qastaging'):
 
190
            return url.replace('bazaar.launchpad.net',
 
191
                               'bazaar.qastaging.launchpad.net')
 
192
        return url
 
193
 
 
194
    @classmethod
 
195
    def from_bzr(cls, launchpad, bzr_branch, create_missing=True):
 
196
        """Find a Launchpad branch from a bzr branch."""
 
197
        check_update = True
 
198
        for url in cls.candidate_urls(bzr_branch):
 
199
            url = cls.tweak_url(url, launchpad)
 
200
            if not cls.plausible_launchpad_url(url):
 
201
                continue
 
202
            lp_branch = launchpad.branches.getByUrl(url=url)
 
203
            if lp_branch is not None:
 
204
                break
 
205
        else:
 
206
            if not create_missing:
 
207
                raise NoLaunchpadBranch(bzr_branch)
 
208
            lp_branch = cls.create_now(launchpad, bzr_branch)
 
209
            check_update = False
 
210
        return cls(lp_branch, bzr_branch.base, bzr_branch, check_update)
 
211
 
 
212
    @classmethod
 
213
    def create_now(cls, launchpad, bzr_branch):
 
214
        """Create a Bazaar branch on Launchpad for the supplied branch."""
 
215
        url = cls.tweak_url(bzr_branch.get_push_location(), launchpad)
 
216
        if not cls.plausible_launchpad_url(url):
 
217
            raise errors.BzrError(gettext('%s is not registered on Launchpad') %
 
218
                                  bzr_branch.base)
 
219
        bzr_branch.create_clone_on_transport(transport.get_transport(url))
 
220
        lp_branch = launchpad.branches.getByUrl(url=url)
 
221
        if lp_branch is None:
 
222
            raise errors.BzrError(gettext('%s is not registered on Launchpad') %
 
223
                                  url)
 
224
        return lp_branch
 
225
 
 
226
    def get_target(self):
 
227
        """Return the 'LaunchpadBranch' for the target of this one."""
 
228
        lp_branch = self.lp
 
229
        if lp_branch.project is not None:
 
230
            dev_focus = lp_branch.project.development_focus
 
231
            if dev_focus is None:
 
232
                raise errors.BzrError(gettext('%s has no development focus.') %
 
233
                                      lp_branch.bzr_identity)
 
234
            target = dev_focus.branch
 
235
            if target is None:
 
236
                raise errors.BzrError(gettext(
 
237
                    'development focus %s has no branch.') % dev_focus)
 
238
        elif lp_branch.sourcepackage is not None:
 
239
            target = lp_branch.sourcepackage.getBranch(pocket="Release")
 
240
            if target is None:
 
241
                raise errors.BzrError(gettext(
 
242
                                      'source package %s has no branch.') %
 
243
                                      lp_branch.sourcepackage)
 
244
        else:
 
245
            raise errors.BzrError(gettext(
 
246
                '%s has no associated product or source package.') %
 
247
                lp_branch.bzr_identity)
 
248
        return LaunchpadBranch(target, target.bzr_identity)
 
249
 
 
250
    def update_lp(self):
 
251
        """Update the Launchpad copy of this branch."""
 
252
        if not self._check_update:
 
253
            return
 
254
        with self.bzr.lock_read():
 
255
            if self.lp.last_scanned_id is not None:
 
256
                if self.bzr.last_revision() == self.lp.last_scanned_id:
 
257
                    trace.note(gettext('%s is already up-to-date.') %
 
258
                               self.lp.bzr_identity)
 
259
                    return
 
260
                graph = self.bzr.repository.get_graph()
 
261
                if not graph.is_ancestor(osutils.safe_utf8(self.lp.last_scanned_id),
 
262
                                         self.bzr.last_revision()):
 
263
                    raise errors.DivergedBranches(self.bzr, self.push_bzr)
 
264
                trace.note(gettext('Pushing to %s') % self.lp.bzr_identity)
 
265
            self.bzr.push(self.push_bzr)
 
266
 
 
267
    def find_lca_tree(self, other):
 
268
        """Find the revision tree for the LCA of this branch and other.
 
269
 
 
270
        :param other: Another LaunchpadBranch
 
271
        :return: The RevisionTree of the LCA of this branch and other.
 
272
        """
 
273
        graph = self.bzr.repository.get_graph(other.bzr.repository)
 
274
        lca = graph.find_unique_lca(self.bzr.last_revision(),
 
275
                                    other.bzr.last_revision())
 
276
        return self.bzr.repository.revision_tree(lca)
 
277
 
 
278
 
 
279
def canonical_url(object):
 
280
    """Return the canonical URL for a branch."""
 
281
    scheme, netloc, path, params, query, fragment = urlparse(
 
282
        str(object.self_link))
 
283
    path = '/'.join(path.split('/')[2:])
 
284
    netloc = netloc.replace('api.', 'code.')
 
285
    return urlunparse((scheme, netloc, path, params, query, fragment))