/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
1
# Copyright (C) 2006-2017 Canonical Ltd
0.4.4 by Martin Pool
Start forming xmlrpc requests
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
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
0.4.4 by Martin Pool
Start forming xmlrpc requests
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.4.4 by Martin Pool
Start forming xmlrpc requests
16
6379.6.3 by Jelmer Vernooij
Use absolute_import.
17
from __future__ import absolute_import
18
7296.2.7 by Jelmer Vernooij
Reuse connection for XMLRPC operations.
19
from io import BytesIO
0.4.17 by Martin Pool
Allow xmlrpc service url to be overridden by $BZR_LP_XMLRPC_URL
20
import os
4505.4.1 by Jonathan Lange
Trap gaierror and reraise appropriate ConnectionError.
21
import socket
6791.2.3 by Jelmer Vernooij
Fix more imports.
22
try:
23
    from urllib.parse import urlsplit, urlunsplit
24
except ImportError:
7143.11.1 by Jelmer Vernooij
Remove some unused imports.
25
    from urlparse import urlsplit, urlunsplit  # noqa: F401
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
26
import urllib
7479.2.1 by Jelmer Vernooij
Drop python2 support.
27
from xmlrpc.client import (
28
    __version__ as xmlrpc_version,
29
    Fault,
30
    ProtocolError,
31
    ServerProxy,
32
    Transport,
33
    )
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
34
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
35
from ... import (
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
36
    errors,
4505.6.3 by Jonathan Lange
Don't bother lazy importing.
37
    urlutils,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
38
    __version__ as _breezy_version,
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
39
    )
7296.2.7 by Jelmer Vernooij
Reuse connection for XMLRPC operations.
40
from ...transport import http, get_transport
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
41
7290.35.1 by Jelmer Vernooij
Allow running tests without launchpadlib installed.
42
from .uris import (
7240.5.7 by Jelmer Vernooij
Move DEFAULT_INSTANCE.
43
    DEFAULT_INSTANCE,
7240.5.3 by Jelmer Vernooij
Move LAUNCHPAD_DOMAINS constant.
44
    LAUNCHPAD_DOMAINS,
45
    LAUNCHPAD_BAZAAR_DOMAINS,
46
    )
47
4505.6.5 by Jonathan Lange
Factor out some code that guesses a branch's URL.
48
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
49
# for testing, do
50
'''
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
51
export BRZ_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
52
'''
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
53
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
54
55
class InvalidURL(errors.PathError):
56
57
    _fmt = 'Invalid url supplied to transport: "%(path)s"%(extra)s'
58
59
3193.5.2 by Tim Penhey
Updated the tests to handle unknown launchpad instances.
60
class InvalidLaunchpadInstance(errors.BzrError):
61
62
    _fmt = "%(lp_instance)s is not a valid Launchpad instance."
63
64
    def __init__(self, lp_instance):
65
        errors.BzrError.__init__(self, lp_instance=lp_instance)
66
67
3955.3.5 by Jonathan Lange
Add an untested plugin, make the error handling a little nicer.
68
class NotLaunchpadBranch(errors.BzrError):
69
4031.2.8 by Jonathan Lange
Say "registered on", not "hosted on".
70
    _fmt = "%(url)s is not registered on Launchpad."
3955.3.5 by Jonathan Lange
Add an untested plugin, make the error handling a little nicer.
71
72
    def __init__(self, url):
73
        errors.BzrError.__init__(self, url=url)
74
75
6973.12.9 by Jelmer Vernooij
More fixes.
76
class XMLRPCTransport(Transport):
4776.2.2 by Vincent Ladeuil
Start testing the XMLRPC transport re-implemented on top of _urllib2_wrappers.
77
4776.3.1 by Vincent Ladeuil
Fix python2.4 compatibility with xmlrpclib.
78
    def __init__(self, scheme):
6973.12.9 by Jelmer Vernooij
More fixes.
79
        Transport.__init__(self)
4776.2.2 by Vincent Ladeuil
Start testing the XMLRPC transport re-implemented on top of _urllib2_wrappers.
80
        self._scheme = scheme
81
        self.verbose = 0
7296.2.7 by Jelmer Vernooij
Reuse connection for XMLRPC operations.
82
        self._possible_bzr_transports = []
4776.2.2 by Vincent Ladeuil
Start testing the XMLRPC transport re-implemented on top of _urllib2_wrappers.
83
84
    def request(self, host, handler, request_body, verbose=0):
85
        self.verbose = verbose
86
        url = self._scheme + "://" + host + handler
7296.2.7 by Jelmer Vernooij
Reuse connection for XMLRPC operations.
87
        transport = get_transport(
88
            url, possible_transports=self._possible_bzr_transports)
89
        response = transport.request("POST", url, body=request_body, headers={
90
            "Content-Type": "text/xml"})
4776.2.2 by Vincent Ladeuil
Start testing the XMLRPC transport re-implemented on top of _urllib2_wrappers.
91
7296.2.7 by Jelmer Vernooij
Reuse connection for XMLRPC operations.
92
        if response.status != 200:
93
            raise ProtocolError(url, response.status,
94
                                response.text, response.headers)
95
        return self.parse_response(BytesIO(response.data))
4776.2.2 by Vincent Ladeuil
Start testing the XMLRPC transport re-implemented on top of _urllib2_wrappers.
96
97
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
98
class LaunchpadService(object):
0.4.27 by Martin Pool
doc
99
    """A service to talk to Launchpad via XMLRPC.
3193.5.2 by Tim Penhey
Updated the tests to handle unknown launchpad instances.
100
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
101
    See http://wiki.bazaar.canonical.com/Specs/LaunchpadRpc for the methods we
102
    can call.
0.4.27 by Martin Pool
doc
103
    """
0.4.6 by Martin Pool
Put the rest of the parameters into the registration request.
104
3211.1.1 by Ian Clatworthy
Extends the launchpad plugin's implementation of lp spec urls (Tim Penhey)
105
    # NB: these should always end in a slash to avoid xmlrpclib appending
0.4.7 by Martin Pool
Start making provision to test using a mock xmlrpc transport.
106
    # '/RPC2'
3955.3.2 by Jonathan Lange
Tighten up the code a little, changing the dev service to use https,
107
    LAUNCHPAD_INSTANCE = {}
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
108
    for instance, domain in LAUNCHPAD_DOMAINS.items():
3955.3.2 by Jonathan Lange
Tighten up the code a little, changing the dev service to use https,
109
        LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
110
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
111
    DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
112
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
113
    transport = None
114
    registrant_email = None
115
    registrant_password = None
116
3193.5.1 by Tim Penhey
Mostly working, just need to update the tests for lp://dev
117
    def __init__(self, transport=None, lp_instance=None):
0.4.23 by Martin Pool
(register-branch) fix ordering of parameters and restore transport-level test.
118
        """Construct a new service talking to the launchpad rpc server"""
3193.5.1 by Tim Penhey
Mostly working, just need to update the tests for lp://dev
119
        self._lp_instance = lp_instance
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
120
        if transport is None:
6973.12.11 by Jelmer Vernooij
Fix some more tests.
121
            uri_type = urlutils.parse_url(self.service_url)[0]
4776.2.6 by Vincent Ladeuil
Fixed as per review comments.
122
            transport = XMLRPCTransport(uri_type)
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
123
        self.transport = transport
124
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
125
    @property
126
    def service_url(self):
127
        """Return the http or https url for the xmlrpc server.
128
129
        This does not include the username/password credentials.
130
        """
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
131
        key = 'BRZ_LP_XMLRPC_URL'
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
132
        if key in os.environ:
133
            return os.environ[key]
3193.5.1 by Tim Penhey
Mostly working, just need to update the tests for lp://dev
134
        elif self._lp_instance is not None:
3193.5.2 by Tim Penhey
Updated the tests to handle unknown launchpad instances.
135
            try:
136
                return self.LAUNCHPAD_INSTANCE[self._lp_instance]
137
            except KeyError:
138
                raise InvalidLaunchpadInstance(self._lp_instance)
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
139
        else:
140
            return self.DEFAULT_SERVICE_URL
141
4505.6.2 by Jonathan Lange
Extract a method that gets a service from a URL.
142
    @classmethod
143
    def for_url(cls, url, **kwargs):
144
        """Return the Launchpad service corresponding to the given URL."""
145
        result = urlsplit(url)
146
        lp_instance = result[1]
147
        if lp_instance == '':
148
            lp_instance = None
149
        elif lp_instance not in cls.LAUNCHPAD_INSTANCE:
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
150
            raise InvalidURL(url)
4505.6.2 by Jonathan Lange
Extract a method that gets a service from a URL.
151
        return cls(lp_instance=lp_instance, **kwargs)
152
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
153
    def get_proxy(self):
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
154
        """Return the proxy for XMLRPC requests."""
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
155
        url = self.service_url
6973.12.9 by Jelmer Vernooij
More fixes.
156
        return ServerProxy(url, transport=self.transport)
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
157
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
158
    def send_request(self, method_name, method_params):
159
        proxy = self.get_proxy()
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
160
        method = getattr(proxy, method_name)
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
161
        try:
162
            result = method(*method_params)
6973.12.9 by Jelmer Vernooij
More fixes.
163
        except ProtocolError as e:
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
164
            if e.errcode == 301:
165
                # TODO: This can give a ProtocolError representing a 301 error, whose
166
                # e.headers['location'] tells where to go and e.errcode==301; should
167
                # probably log something and retry on the new url.
168
                raise NotImplementedError("should resend request to %s, but this isn't implemented"
7143.15.2 by Jelmer Vernooij
Run autopep8.
169
                                          % e.headers.get('Location', 'NO-LOCATION-PRESENT'))
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
170
            else:
171
                # we don't want to print the original message because its
172
                # str representation includes the plaintext password.
173
                # TODO: print more headers to help in tracking down failures
174
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
7143.15.2 by Jelmer Vernooij
Run autopep8.
175
                                      % (self.service_url, e.errcode, e.errmsg))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
176
        except socket.gaierror as e:
4505.4.1 by Jonathan Lange
Trap gaierror and reraise appropriate ConnectionError.
177
            raise errors.ConnectionError(
178
                "Could not resolve '%s'" % self.domain,
179
                orig_error=e)
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
180
        return result
181
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
182
    @property
183
    def domain(self):
184
        if self._lp_instance is None:
7240.5.7 by Jelmer Vernooij
Move DEFAULT_INSTANCE.
185
            instance = DEFAULT_INSTANCE
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
186
        else:
187
            instance = self._lp_instance
7240.5.3 by Jelmer Vernooij
Move LAUNCHPAD_DOMAINS constant.
188
        return LAUNCHPAD_DOMAINS[instance]
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
189
4505.6.5 by Jonathan Lange
Factor out some code that guesses a branch's URL.
190
    def _guess_branch_path(self, branch_url, _request_factory=None):
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
191
        scheme, hostinfo, path = urlsplit(branch_url)[:3]
3955.3.8 by Jonathan Lange
Support lp URL shortcuts.
192
        if _request_factory is None:
193
            _request_factory = ResolveLaunchpadPathRequest
194
        if scheme == 'lp':
195
            resolve = _request_factory(path)
3955.3.9 by Jonathan Lange
Catch errors.
196
            try:
197
                result = resolve.submit(self)
6973.12.9 by Jelmer Vernooij
More fixes.
198
            except Fault as fault:
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
199
                raise InvalidURL(branch_url, str(fault))
3955.3.8 by Jonathan Lange
Support lp URL shortcuts.
200
            branch_url = result['urls'][0]
201
            path = urlsplit(branch_url)[2]
202
        else:
7240.5.3 by Jelmer Vernooij
Move LAUNCHPAD_DOMAINS constant.
203
            if hostinfo not in LAUNCHPAD_BAZAAR_DOMAINS:
3955.3.5 by Jonathan Lange
Add an untested plugin, make the error handling a little nicer.
204
                raise NotLaunchpadBranch(branch_url)
4505.6.5 by Jonathan Lange
Factor out some code that guesses a branch's URL.
205
        return path.lstrip('/')
206
207
    def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
208
        """Get the Launchpad web URL for the given branch URL.
209
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
210
        :raise InvalidURL: if 'branch_url' cannot be identified as a
4505.6.5 by Jonathan Lange
Factor out some code that guesses a branch's URL.
211
            Launchpad branch URL.
212
        :return: The URL of the branch on Launchpad.
213
        """
214
        path = self._guess_branch_path(branch_url, _request_factory)
3955.3.7 by Jonathan Lange
Test the launchpad-open command. Fix up some minor bugs.
215
        return urlutils.join('https://code.%s' % self.domain, path)
3955.3.1 by Jonathan Lange
Start doing URL stuff, extracting the domain bit out of LaunchpadService,
216
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
217
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
218
class BaseRequest(object):
219
    """Base request for talking to a XMLRPC server."""
220
221
    # Set this to the XMLRPC method name.
222
    _methodname = None
223
224
    def _request_params(self):
225
        """Return the arguments to pass to the method"""
226
        raise NotImplementedError(self._request_params)
227
228
    def submit(self, service):
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
229
        """Submit request to Launchpad XMLRPC server.
230
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
231
        :param service: LaunchpadService indicating where to send the request.
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
232
        """
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
233
        return service.send_request(self._methodname, self._request_params())
0.4.19 by test at canonical
add possibility to link to a bug when registering a branch. factor out some common functionality from BranchRegistrationRequest.
234
235
1668.1.12 by Martin Pool
(launchpad plugin) Improved --dry-run that uses a dummy xmlrpc service.
236
class DryRunLaunchpadService(LaunchpadService):
6622.7.1 by Colin Watson
Remove `bzr register-branch`, since it has not worked for a long time.
237
    """Service that just absorbs requests without sending to server."""
238
239
    def send_request(self, method_name, method_params):
240
        pass
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
241
242
2898.4.3 by James Henstridge
Make launchpad_transport_indirect() use XMLRPC to resolve the lp: URL.
243
class ResolveLaunchpadPathRequest(BaseRequest):
244
    """Request to resolve the path component of an lp: URL."""
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
245
2898.4.3 by James Henstridge
Make launchpad_transport_indirect() use XMLRPC to resolve the lp: URL.
246
    _methodname = 'resolve_lp_path'
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
247
248
    def __init__(self, path):
3246.4.1 by Daniel Watkins
Replaced problematic assertion with exception call.
249
        if not path:
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
250
            raise InvalidURL(url=path, extra="You must specify a project.")
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
251
        self.path = path
252
253
    def _request_params(self):
254
        """Return xmlrpc request parameters"""
255
        return (self.path,)