/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2006 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
0.4.14 by Martin Pool
Update xmlrpc api
18
from getpass import getpass
0.4.17 by Martin Pool
Allow xmlrpc service url to be overridden by $BZR_LP_XMLRPC_URL
19
import os
0.4.7 by Martin Pool
Start making provision to test using a mock xmlrpc transport.
20
from urlparse import urlsplit, urlunsplit
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
21
import urllib
0.4.4 by Martin Pool
Start forming xmlrpc requests
22
import xmlrpclib
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
23
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
24
from bzrlib import (
25
    config,
26
    errors,
2900.2.22 by Vincent Ladeuil
Polishing.
27
    __version__ as _bzrlib_version,
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
28
    )
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
29
30
# for testing, do
31
'''
32
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
33
'''
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
34
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.
35
class LaunchpadService(object):
0.4.27 by Martin Pool
doc
36
    """A service to talk to Launchpad via XMLRPC.
37
    
38
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
39
    """
0.4.6 by Martin Pool
Put the rest of the parameters into the registration request.
40
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
41
    # NB: this 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.
42
    # '/RPC2'
1668.1.11 by Martin Pool
(launchpad) default xmlrpc service url should be https
43
    DEFAULT_SERVICE_URL = 'https://xmlrpc.launchpad.net/bazaar/'
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
44
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.
45
    transport = None
46
    registrant_email = None
47
    registrant_password = None
48
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
49
50
    def __init__(self, transport=None):
0.4.23 by Martin Pool
(register-branch) fix ordering of parameters and restore transport-level test.
51
        """Construct a new service talking to the launchpad rpc server"""
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
52
        if transport is None:
53
            uri_type = urllib.splittype(self.service_url)[0]
54
            if uri_type == 'https':
55
                transport = xmlrpclib.SafeTransport()
56
            else:
57
                transport = xmlrpclib.Transport()
58
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
2900.2.22 by Vincent Ladeuil
Polishing.
59
                    % (_bzrlib_version, xmlrpclib.__version__)
0.4.29 by Martin Pool
(register-branch) override xmlrpc user-agent; move Transport construction
60
        self.transport = transport
61
0.4.23 by Martin Pool
(register-branch) fix ordering of parameters and restore transport-level test.
62
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.
63
    @property
64
    def service_url(self):
65
        """Return the http or https url for the xmlrpc server.
66
67
        This does not include the username/password credentials.
68
        """
69
        key = 'BZR_LP_XMLRPC_URL'
70
        if key in os.environ:
71
            return os.environ[key]
72
        else:
73
            return self.DEFAULT_SERVICE_URL
74
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
75
    def get_proxy(self, authenticated):
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.
76
        """Return the proxy for XMLRPC requests."""
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
77
        if authenticated:
78
            # auth info must be in url
79
            # TODO: if there's no registrant email perhaps we should
80
            # just connect anonymously?
81
            scheme, hostinfo, path = urlsplit(self.service_url)[:3]
82
            assert '@' not in hostinfo
83
            assert self.registrant_email is not None
84
            assert self.registrant_password is not None
85
            # TODO: perhaps fully quote the password to make it very slightly
86
            # obscured
87
            # TODO: can we perhaps add extra Authorization headers
88
            # directly to the request, rather than putting this into
89
            # the url?  perhaps a bit more secure against accidentally
90
            # revealing it.  std66 s3.2.1 discourages putting the
91
            # password in the url.
92
            hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
93
                                     urllib.quote(self.registrant_password),
94
                                     hostinfo)
95
            url = urlunsplit((scheme, hostinfo, path, '', ''))
96
        else:
97
            url = self.service_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.
98
        return xmlrpclib.ServerProxy(url, transport=self.transport)
99
100
    def gather_user_credentials(self):
101
        """Get the password from the user."""
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
102
        config = config.GlobalConfig()
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.
103
        self.registrant_email = config.user_email()
104
        if self.registrant_password is None:
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
105
            auth = config.AuthenticationConfig()
106
            scheme, hostinfo = urlsplit(self.service_url)[:2]
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.
107
            prompt = 'launchpad.net password for %s: ' % \
108
                    self.registrant_email
2900.2.21 by Vincent Ladeuil
Make lp_registration aware of authentication config.
109
            # We will reuse http[s] credentials if we can, prompt user
110
            # otherwise
111
            self.registrant_password = auth.get_password(scheme, hostinfo,
112
                                                         prompt=prompt)
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
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
114
    def send_request(self, method_name, method_params, authenticated):
115
        proxy = self.get_proxy(authenticated)
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
116
        assert method_name
117
        method = getattr(proxy, method_name)
1668.1.9 by Martin Pool
(launchpad plugin) Better reporting of errors from xmlrpc
118
        try:
119
            result = method(*method_params)
120
        except xmlrpclib.ProtocolError, e:
121
            if e.errcode == 301:
122
                # TODO: This can give a ProtocolError representing a 301 error, whose
123
                # e.headers['location'] tells where to go and e.errcode==301; should
124
                # probably log something and retry on the new url.
125
                raise NotImplementedError("should resend request to %s, but this isn't implemented"
126
                        % e.headers.get('Location', 'NO-LOCATION-PRESENT'))
127
            else:
128
                # we don't want to print the original message because its
129
                # str representation includes the plaintext password.
130
                # TODO: print more headers to help in tracking down failures
131
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
132
                        % (self.service_url, e.errcode, e.errmsg))
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
133
        return result
134
135
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.
136
class BaseRequest(object):
137
    """Base request for talking to a XMLRPC server."""
138
139
    # Set this to the XMLRPC method name.
140
    _methodname = None
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
141
    _authenticated = True
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.
142
143
    def _request_params(self):
144
        """Return the arguments to pass to the method"""
145
        raise NotImplementedError(self._request_params)
146
147
    def submit(self, service):
0.4.21 by Martin Pool
Refactor BaseRequest.submit so details of submission are in the LaunchpadService
148
        """Submit request to Launchpad XMLRPC server.
149
150
        :param service: LaunchpadService indicating where to send
151
            the request and the authentication credentials.
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.
152
        """
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
153
        return service.send_request(self._methodname, self._request_params(),
154
                                    self._authenticated)
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.
155
156
1668.1.12 by Martin Pool
(launchpad plugin) Improved --dry-run that uses a dummy xmlrpc service.
157
class DryRunLaunchpadService(LaunchpadService):
158
    """Service that just absorbs requests without sending to server.
159
    
160
    The dummy service does not need authentication.
161
    """
162
2898.4.1 by James Henstridge
Make it possible to make unauthenticated XML-RPC requests.
163
    def send_request(self, method_name, method_params, authenticated):
1668.1.12 by Martin Pool
(launchpad plugin) Improved --dry-run that uses a dummy xmlrpc service.
164
        pass
165
166
    def gather_user_credentials(self):
167
        pass
168
169
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.
170
class BranchRegistrationRequest(BaseRequest):
171
    """Request to tell Launchpad about a bzr branch."""
172
173
    _methodname = 'register_branch'
0.4.7 by Martin Pool
Start making provision to test using a mock xmlrpc transport.
174
0.4.23 by Martin Pool
(register-branch) fix ordering of parameters and restore transport-level test.
175
    def __init__(self, branch_url,
0.4.15 by Martin Pool
(register-branch) Add command-line options
176
                 branch_name='',
177
                 branch_title='',
178
                 branch_description='',
0.4.23 by Martin Pool
(register-branch) fix ordering of parameters and restore transport-level test.
179
                 author_email='',
0.4.15 by Martin Pool
(register-branch) Add command-line options
180
                 product_name='',
181
                 ):
0.4.14 by Martin Pool
Update xmlrpc api
182
        assert branch_url
0.4.4 by Martin Pool
Start forming xmlrpc requests
183
        self.branch_url = branch_url
0.4.15 by Martin Pool
(register-branch) Add command-line options
184
        if branch_name:
185
            self.branch_name = branch_name
0.4.14 by Martin Pool
Update xmlrpc api
186
        else:
0.4.15 by Martin Pool
(register-branch) Add command-line options
187
            self.branch_name = self._find_default_branch_name(self.branch_url)
188
        self.branch_title = branch_title
189
        self.branch_description = branch_description
190
        self.author_email = author_email
191
        self.product_name = product_name
0.4.4 by Martin Pool
Start forming xmlrpc requests
192
193
    def _request_params(self):
194
        """Return xmlrpc request parameters"""
0.4.6 by Martin Pool
Put the rest of the parameters into the registration request.
195
        # This must match the parameter tuple expected by Launchpad for this
196
        # method
0.4.4 by Martin Pool
Start forming xmlrpc requests
197
        return (self.branch_url,
0.4.15 by Martin Pool
(register-branch) Add command-line options
198
                self.branch_name,
0.4.14 by Martin Pool
Update xmlrpc api
199
                self.branch_title,
0.4.6 by Martin Pool
Put the rest of the parameters into the registration request.
200
                self.branch_description,
0.4.14 by Martin Pool
Update xmlrpc api
201
                self.author_email,
0.4.13 by Martin Pool
Update xmlrpc api to pass product name as a parameter.
202
                self.product_name,
0.4.4 by Martin Pool
Start forming xmlrpc requests
203
               )
204
0.4.15 by Martin Pool
(register-branch) Add command-line options
205
    def _find_default_branch_name(self, branch_url):
0.4.14 by Martin Pool
Update xmlrpc api
206
        i = branch_url.rfind('/')
207
        return branch_url[i+1:]
208
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.
209
210
class BranchBugLinkRequest(BaseRequest):
211
    """Request to link a bzr branch in Launchpad to a bug."""
212
213
    _methodname = 'link_branch_to_bug'
214
215
    def __init__(self, branch_url, bug_id):
216
        assert branch_url
0.4.26 by Martin Pool
(register-branch) Add test for link_branch_to_bug and fix its parameters
217
        self.bug_id = bug_id
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
        self.branch_url = branch_url
219
220
    def _request_params(self):
221
        """Return xmlrpc request parameters"""
222
        # This must match the parameter tuple expected by Launchpad for this
223
        # method
224
        return (self.branch_url, self.bug_id, '')
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
225
226
2898.4.3 by James Henstridge
Make launchpad_transport_indirect() use XMLRPC to resolve the lp: URL.
227
class ResolveLaunchpadPathRequest(BaseRequest):
228
    """Request to resolve the path component of an lp: URL."""
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
229
2898.4.3 by James Henstridge
Make launchpad_transport_indirect() use XMLRPC to resolve the lp: URL.
230
    _methodname = 'resolve_lp_path'
2898.4.2 by James Henstridge
Add ResolveLaunchpadURLRequest() class to handle lp: URL resolution.
231
    _authenticated = False
232
233
    def __init__(self, path):
234
        assert path
235
        self.path = path
236
237
    def _request_params(self):
238
        """Return xmlrpc request parameters"""
239
        return (self.path,)