~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugins/launchpad/lp_registration.py

  • Committer: Vincent Ladeuil
  • Date: 2009-12-14 15:51:36 UTC
  • mto: (4894.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4895.
  • Revision ID: v.ladeuil+lp@free.fr-20091214155136-rf4nkqvxda9oiw4u
Cleanup tests and tweak the text displayed.

* bzrlib/tests/blackbox/test_update.py:
Fix imports and replace the assertContainsRe with assertEqualDiff
to make the test clearer, more robust and easier to debug.

* bzrlib/tests/commands/test_update.py: 
Fix imports.

* bzrlib/tests/blackbox/test_filtered_view_ops.py: 
Fix imports and strange accesses to base class methods.
(TestViewTreeOperations.test_view_on_update): Avoid os.chdir()
call, simplify string matching assertions.

* bzrlib/builtins.py:
(cmd_update.run): Fix spurious space, get rid of the final '/' for
the base path, don't add a final period (it's a legal char in a
path and would be annoying for people that like to copy/paste).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 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
 
 
18
import os
 
19
import socket
 
20
from urlparse import urlsplit, urlunsplit
 
21
import urllib
 
22
import xmlrpclib
 
23
 
 
24
from bzrlib.lazy_import import lazy_import
 
25
lazy_import(globals(), """
 
26
from bzrlib import urlutils
 
27
""")
 
28
 
 
29
from bzrlib import (
 
30
    config,
 
31
    errors,
 
32
    __version__ as _bzrlib_version,
 
33
    )
 
34
from bzrlib.transport.http import _urllib2_wrappers
 
35
 
 
36
# for testing, do
 
37
'''
 
38
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
 
39
'''
 
40
 
 
41
class InvalidLaunchpadInstance(errors.BzrError):
 
42
 
 
43
    _fmt = "%(lp_instance)s is not a valid Launchpad instance."
 
44
 
 
45
    def __init__(self, lp_instance):
 
46
        errors.BzrError.__init__(self, lp_instance=lp_instance)
 
47
 
 
48
 
 
49
class NotLaunchpadBranch(errors.BzrError):
 
50
 
 
51
    _fmt = "%(url)s is not registered on Launchpad."
 
52
 
 
53
    def __init__(self, url):
 
54
        errors.BzrError.__init__(self, url=url)
 
55
 
 
56
 
 
57
class XMLRPCTransport(xmlrpclib.Transport):
 
58
 
 
59
    def __init__(self, scheme):
 
60
        # In python2.4 xmlrpclib.Transport is a old-style class, and does not
 
61
        # define __init__, so we check first
 
62
        init = getattr(xmlrpclib.Transport, '__init__', None)
 
63
        if init is not None:
 
64
            init(self)
 
65
        self._scheme = scheme
 
66
        self._opener = _urllib2_wrappers.Opener()
 
67
        self.verbose = 0
 
68
 
 
69
    def request(self, host, handler, request_body, verbose=0):
 
70
        self.verbose = verbose
 
71
        url = self._scheme + "://" + host + handler
 
72
        request = _urllib2_wrappers.Request("POST", url, request_body)
 
73
        # FIXME: _urllib2_wrappers will override user-agent with its own
 
74
        # request.add_header("User-Agent", self.user_agent)
 
75
        request.add_header("Content-Type", "text/xml")
 
76
 
 
77
        response = self._opener.open(request)
 
78
        if response.code != 200:
 
79
            raise xmlrpclib.ProtocolError(host + handler, response.code,
 
80
                                          response.msg, response.info())
 
81
        return self.parse_response(response)
 
82
 
 
83
 
 
84
class LaunchpadService(object):
 
85
    """A service to talk to Launchpad via XMLRPC.
 
86
 
 
87
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
 
88
    """
 
89
 
 
90
    LAUNCHPAD_DOMAINS = {
 
91
        'production': 'launchpad.net',
 
92
        'edge': 'edge.launchpad.net',
 
93
        'staging': 'staging.launchpad.net',
 
94
        'demo': 'demo.launchpad.net',
 
95
        'dev': 'launchpad.dev',
 
96
        }
 
97
 
 
98
    # NB: these should always end in a slash to avoid xmlrpclib appending
 
99
    # '/RPC2'
 
100
    LAUNCHPAD_INSTANCE = {}
 
101
    for instance, domain in LAUNCHPAD_DOMAINS.iteritems():
 
102
        LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
 
103
 
 
104
    # We use edge as the default because:
 
105
    # Beta users get redirected to it
 
106
    # All users can use it
 
107
    # There is a bug in the launchpad side where redirection causes an OOPS.
 
108
    DEFAULT_INSTANCE = 'edge'
 
109
    DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
 
110
 
 
111
    transport = None
 
112
    registrant_email = None
 
113
    registrant_password = None
 
114
 
 
115
 
 
116
    def __init__(self, transport=None, lp_instance=None):
 
117
        """Construct a new service talking to the launchpad rpc server"""
 
118
        self._lp_instance = lp_instance
 
119
        if transport is None:
 
120
            uri_type = urllib.splittype(self.service_url)[0]
 
121
            transport = XMLRPCTransport(uri_type)
 
122
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
 
123
                    % (_bzrlib_version, xmlrpclib.__version__)
 
124
        self.transport = transport
 
125
 
 
126
 
 
127
    @property
 
128
    def service_url(self):
 
129
        """Return the http or https url for the xmlrpc server.
 
130
 
 
131
        This does not include the username/password credentials.
 
132
        """
 
133
        key = 'BZR_LP_XMLRPC_URL'
 
134
        if key in os.environ:
 
135
            return os.environ[key]
 
136
        elif self._lp_instance is not None:
 
137
            try:
 
138
                return self.LAUNCHPAD_INSTANCE[self._lp_instance]
 
139
            except KeyError:
 
140
                raise InvalidLaunchpadInstance(self._lp_instance)
 
141
        else:
 
142
            return self.DEFAULT_SERVICE_URL
 
143
 
 
144
    def get_proxy(self, authenticated):
 
145
        """Return the proxy for XMLRPC requests."""
 
146
        if authenticated:
 
147
            # auth info must be in url
 
148
            # TODO: if there's no registrant email perhaps we should
 
149
            # just connect anonymously?
 
150
            scheme, hostinfo, path = urlsplit(self.service_url)[:3]
 
151
            if '@' in hostinfo:
 
152
                raise AssertionError(hostinfo)
 
153
            if self.registrant_email is None:
 
154
                raise AssertionError()
 
155
            if self.registrant_password is None:
 
156
                raise AssertionError()
 
157
            # TODO: perhaps fully quote the password to make it very slightly
 
158
            # obscured
 
159
            # TODO: can we perhaps add extra Authorization headers
 
160
            # directly to the request, rather than putting this into
 
161
            # the url?  perhaps a bit more secure against accidentally
 
162
            # revealing it.  std66 s3.2.1 discourages putting the
 
163
            # password in the url.
 
164
            hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
 
165
                                     urllib.quote(self.registrant_password),
 
166
                                     hostinfo)
 
167
            url = urlunsplit((scheme, hostinfo, path, '', ''))
 
168
        else:
 
169
            url = self.service_url
 
170
        return xmlrpclib.ServerProxy(url, transport=self.transport)
 
171
 
 
172
    def gather_user_credentials(self):
 
173
        """Get the password from the user."""
 
174
        the_config = config.GlobalConfig()
 
175
        self.registrant_email = the_config.user_email()
 
176
        if self.registrant_password is None:
 
177
            auth = config.AuthenticationConfig()
 
178
            scheme, hostinfo = urlsplit(self.service_url)[:2]
 
179
            prompt = 'launchpad.net password for %s: ' % \
 
180
                    self.registrant_email
 
181
            # We will reuse http[s] credentials if we can, prompt user
 
182
            # otherwise
 
183
            self.registrant_password = auth.get_password(scheme, hostinfo,
 
184
                                                         self.registrant_email,
 
185
                                                         prompt=prompt)
 
186
 
 
187
    def send_request(self, method_name, method_params, authenticated):
 
188
        proxy = self.get_proxy(authenticated)
 
189
        method = getattr(proxy, method_name)
 
190
        try:
 
191
            result = method(*method_params)
 
192
        except xmlrpclib.ProtocolError, e:
 
193
            if e.errcode == 301:
 
194
                # TODO: This can give a ProtocolError representing a 301 error, whose
 
195
                # e.headers['location'] tells where to go and e.errcode==301; should
 
196
                # probably log something and retry on the new url.
 
197
                raise NotImplementedError("should resend request to %s, but this isn't implemented"
 
198
                        % e.headers.get('Location', 'NO-LOCATION-PRESENT'))
 
199
            else:
 
200
                # we don't want to print the original message because its
 
201
                # str representation includes the plaintext password.
 
202
                # TODO: print more headers to help in tracking down failures
 
203
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
 
204
                        % (self.service_url, e.errcode, e.errmsg))
 
205
        except socket.gaierror, e:
 
206
            raise errors.ConnectionError(
 
207
                "Could not resolve '%s'" % self.domain,
 
208
                orig_error=e)
 
209
        return result
 
210
 
 
211
    @property
 
212
    def domain(self):
 
213
        if self._lp_instance is None:
 
214
            instance = self.DEFAULT_INSTANCE
 
215
        else:
 
216
            instance = self._lp_instance
 
217
        return self.LAUNCHPAD_DOMAINS[instance]
 
218
 
 
219
    def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
 
220
        """Get the Launchpad web URL for the given branch URL.
 
221
 
 
222
        :raise errors.InvalidURL: if 'branch_url' cannot be identified as a
 
223
            Launchpad branch URL.
 
224
        :return: The URL of the branch on Launchpad.
 
225
        """
 
226
        scheme, hostinfo, path = urlsplit(branch_url)[:3]
 
227
        if _request_factory is None:
 
228
            _request_factory = ResolveLaunchpadPathRequest
 
229
        if scheme == 'lp':
 
230
            resolve = _request_factory(path)
 
231
            try:
 
232
                result = resolve.submit(self)
 
233
            except xmlrpclib.Fault, fault:
 
234
                raise errors.InvalidURL(branch_url, str(fault))
 
235
            branch_url = result['urls'][0]
 
236
            path = urlsplit(branch_url)[2]
 
237
        else:
 
238
            domains = (
 
239
                'bazaar.%s' % domain
 
240
                for domain in self.LAUNCHPAD_DOMAINS.itervalues())
 
241
            if hostinfo not in domains:
 
242
                raise NotLaunchpadBranch(branch_url)
 
243
        return urlutils.join('https://code.%s' % self.domain, path)
 
244
 
 
245
 
 
246
class BaseRequest(object):
 
247
    """Base request for talking to a XMLRPC server."""
 
248
 
 
249
    # Set this to the XMLRPC method name.
 
250
    _methodname = None
 
251
    _authenticated = True
 
252
 
 
253
    def _request_params(self):
 
254
        """Return the arguments to pass to the method"""
 
255
        raise NotImplementedError(self._request_params)
 
256
 
 
257
    def submit(self, service):
 
258
        """Submit request to Launchpad XMLRPC server.
 
259
 
 
260
        :param service: LaunchpadService indicating where to send
 
261
            the request and the authentication credentials.
 
262
        """
 
263
        return service.send_request(self._methodname, self._request_params(),
 
264
                                    self._authenticated)
 
265
 
 
266
 
 
267
class DryRunLaunchpadService(LaunchpadService):
 
268
    """Service that just absorbs requests without sending to server.
 
269
 
 
270
    The dummy service does not need authentication.
 
271
    """
 
272
 
 
273
    def send_request(self, method_name, method_params, authenticated):
 
274
        pass
 
275
 
 
276
    def gather_user_credentials(self):
 
277
        pass
 
278
 
 
279
 
 
280
class BranchRegistrationRequest(BaseRequest):
 
281
    """Request to tell Launchpad about a bzr branch."""
 
282
 
 
283
    _methodname = 'register_branch'
 
284
 
 
285
    def __init__(self, branch_url,
 
286
                 branch_name='',
 
287
                 branch_title='',
 
288
                 branch_description='',
 
289
                 author_email='',
 
290
                 product_name='',
 
291
                 ):
 
292
        if not branch_url:
 
293
            raise errors.InvalidURL(branch_url, "You need to specify a non-empty branch URL.")
 
294
        self.branch_url = branch_url
 
295
        if branch_name:
 
296
            self.branch_name = branch_name
 
297
        else:
 
298
            self.branch_name = self._find_default_branch_name(self.branch_url)
 
299
        self.branch_title = branch_title
 
300
        self.branch_description = branch_description
 
301
        self.author_email = author_email
 
302
        self.product_name = product_name
 
303
 
 
304
    def _request_params(self):
 
305
        """Return xmlrpc request parameters"""
 
306
        # This must match the parameter tuple expected by Launchpad for this
 
307
        # method
 
308
        return (self.branch_url,
 
309
                self.branch_name,
 
310
                self.branch_title,
 
311
                self.branch_description,
 
312
                self.author_email,
 
313
                self.product_name,
 
314
               )
 
315
 
 
316
    def _find_default_branch_name(self, branch_url):
 
317
        i = branch_url.rfind('/')
 
318
        return branch_url[i+1:]
 
319
 
 
320
 
 
321
class BranchBugLinkRequest(BaseRequest):
 
322
    """Request to link a bzr branch in Launchpad to a bug."""
 
323
 
 
324
    _methodname = 'link_branch_to_bug'
 
325
 
 
326
    def __init__(self, branch_url, bug_id):
 
327
        self.bug_id = bug_id
 
328
        self.branch_url = branch_url
 
329
 
 
330
    def _request_params(self):
 
331
        """Return xmlrpc request parameters"""
 
332
        # This must match the parameter tuple expected by Launchpad for this
 
333
        # method
 
334
        return (self.branch_url, self.bug_id, '')
 
335
 
 
336
 
 
337
class ResolveLaunchpadPathRequest(BaseRequest):
 
338
    """Request to resolve the path component of an lp: URL."""
 
339
 
 
340
    _methodname = 'resolve_lp_path'
 
341
    _authenticated = False
 
342
 
 
343
    def __init__(self, path):
 
344
        if not path:
 
345
            raise errors.InvalidURL(path=path,
 
346
                                    extra="You must specify a project.")
 
347
        self.path = path
 
348
 
 
349
    def _request_params(self):
 
350
        """Return xmlrpc request parameters"""
 
351
        return (self.path,)