blob: 89cb2d410c48d986083769b8feec977fbf89a13a [file] [log] [blame]
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +00001"""distutils.command.register
2
3Implements the Distutils 'register' command (register with the repository).
4"""
5
6# created 2002/10/21, Richard Jones
7
8__revision__ = "$Id$"
9
Christian Heimes05e8be12008-02-23 18:30:17 +000010import os, string, urllib2, getpass, urlparse
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011import io
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000012
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000013from distutils.core import PyPIRCCommand
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000014from distutils.errors import *
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000015from distutils import log
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000016
Neal Norwitzce96f692006-03-17 06:49:51 +000017def raw_input(prompt):
18 sys.stdout.write(prompt)
19 sys.stdout.flush()
20 return sys.stdin.readline()
21
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000022class register(PyPIRCCommand):
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000023
Andrew M. Kuchlinga9ccce32003-03-03 18:26:01 +000024 description = ("register the distribution with the Python package index")
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000025 user_options = PyPIRCCommand.user_options + [
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000026 ('list-classifiers', None,
27 'list the valid Trove classifiers'),
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000028 ]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000029 boolean_options = PyPIRCCommand.boolean_options + [
30 'verify', 'list-classifiers']
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000031
32 def initialize_options(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000033 PyPIRCCommand.initialize_options(self)
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000034 self.list_classifiers = 0
35
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000036 def run(self):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000037 self.finalize_options()
38 self._set_config()
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000039 self.check_metadata()
Andrew M. Kuchling058a84f2003-04-09 12:35:51 +000040 if self.dry_run:
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000041 self.verify_metadata()
42 elif self.list_classifiers:
43 self.classifiers()
44 else:
45 self.send_metadata()
46
47 def check_metadata(self):
48 """Ensure that all required elements of meta-data (name, version,
49 URL, (author and author_email) or (maintainer and
50 maintainer_email)) are supplied by the Distribution object; warn if
51 any are missing.
52 """
53 metadata = self.distribution.metadata
54
55 missing = []
56 for attr in ('name', 'version', 'url'):
57 if not (hasattr(metadata, attr) and getattr(metadata, attr)):
58 missing.append(attr)
59
60 if missing:
61 self.warn("missing required meta-data: " +
Neal Norwitz9d72bb42007-04-17 08:48:32 +000062 ", ".join(missing))
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000063
64 if metadata.author:
65 if not metadata.author_email:
66 self.warn("missing meta-data: if 'author' supplied, " +
67 "'author_email' must be supplied too")
68 elif metadata.maintainer:
69 if not metadata.maintainer_email:
70 self.warn("missing meta-data: if 'maintainer' supplied, " +
71 "'maintainer_email' must be supplied too")
72 else:
73 self.warn("missing meta-data: either (author and author_email) " +
74 "or (maintainer and maintainer_email) " +
75 "must be supplied")
76
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000077 def _set_config(self):
78 ''' Reads the configuration file and set attributes.
79 '''
80 config = self._read_pypirc()
81 if config != {}:
82 self.username = config['username']
83 self.password = config['password']
84 self.repository = config['repository']
85 self.realm = config['realm']
86 self.has_config = True
87 else:
88 if self.repository not in ('pypi', self.DEFAULT_REPOSITORY):
89 raise ValueError('%s not found in .pypirc' % self.repository)
90 if self.repository == 'pypi':
91 self.repository = self.DEFAULT_REPOSITORY
92 self.has_config = False
93
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000094 def classifiers(self):
95 ''' Fetch the list of classifiers from the server.
96 '''
97 response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
Guido van Rossumbe19ed72007-02-09 05:37:30 +000098 print(response.read())
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +000099
100 def verify_metadata(self):
101 ''' Send the metadata to the package index server to be checked.
102 '''
103 # send the info to the server and report the result
104 (code, result) = self.post_to_server(self.build_post_data('verify'))
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000105 print('Server response (%s): %s'%(code, result))
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000106
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000107
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000108 def send_metadata(self):
109 ''' Send the metadata to the package index server.
110
111 Well, do the following:
112 1. figure who the user is, and then
113 2. send the data as a Basic auth'ed POST.
114
115 First we try to read the username/password from $HOME/.pypirc,
116 which is a ConfigParser-formatted file with a section
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000117 [distutils] containing username and password entries (both
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000118 in clear text). Eg:
119
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000120 [distutils]
121 index-servers =
122 pypi
123
124 [pypi]
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000125 username: fred
126 password: sekrit
127
128 Otherwise, to figure who the user is, we offer the user three
129 choices:
130
131 1. use existing login,
132 2. register as a new user, or
133 3. set the password to a random string and email the user.
134
135 '''
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000136 # see if we can short-cut and get the username/password from the
137 # config
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000138 if self.has_config:
139 choice = '1'
140 username = self.username
141 password = self.password
142 else:
143 choice = 'x'
144 username = password = ''
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000145
146 # get the user's login info
147 choices = '1 2 3 4'.split()
148 while choice not in choices:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print('''We need to know who you are, so please choose either:
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000150 1. use your existing login,
151 2. register as a new user,
152 3. have the server generate a new password for you (and email it to you), or
153 4. quit
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154Your selection [default 1]: ''', end=' ')
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000155 choice = raw_input()
156 if not choice:
157 choice = '1'
158 elif choice not in choices:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000159 print('Please choose one of the four options!')
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000160
161 if choice == '1':
162 # get the username and password
163 while not username:
164 username = raw_input('Username: ')
165 while not password:
166 password = getpass.getpass('Password: ')
167
168 # set up the authentication
169 auth = urllib2.HTTPPasswordMgr()
170 host = urlparse.urlparse(self.repository)[1]
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000171 auth.add_password(self.realm, host, username, password)
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000172 # send the info to the server and report the result
173 code, result = self.post_to_server(self.build_post_data('submit'),
174 auth)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000175 print('Server response (%s): %s'%(code, result))
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000176
177 # possibly save the login
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000178 if not self.has_config and code == 200:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000179 print('I can store your PyPI login so future submissions will be faster.')
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000180 print('(the login will be stored in %s)' % self._get_rc_file())
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000181 choice = 'X'
182 while choice.lower() not in 'yn':
183 choice = raw_input('Save your login (y/N)?')
184 if not choice:
185 choice = 'n'
186 if choice.lower() == 'y':
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000187 self._store_pypirc(username, password)
188
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000189 elif choice == '2':
190 data = {':action': 'user'}
191 data['name'] = data['password'] = data['email'] = ''
192 data['confirm'] = None
193 while not data['name']:
194 data['name'] = raw_input('Username: ')
195 while data['password'] != data['confirm']:
196 while not data['password']:
197 data['password'] = getpass.getpass('Password: ')
198 while not data['confirm']:
199 data['confirm'] = getpass.getpass(' Confirm: ')
200 if data['password'] != data['confirm']:
201 data['password'] = ''
202 data['confirm'] = None
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000203 print("Password and confirm don't match!")
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000204 while not data['email']:
205 data['email'] = raw_input(' EMail: ')
206 code, result = self.post_to_server(data)
207 if code != 200:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000208 print('Server response (%s): %s'%(code, result))
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000209 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000210 print('You will receive an email shortly.')
211 print('Follow the instructions in it to complete registration.')
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000212 elif choice == '3':
213 data = {':action': 'password_reset'}
214 data['email'] = ''
215 while not data['email']:
216 data['email'] = raw_input('Your email address: ')
217 code, result = self.post_to_server(data)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000218 print('Server response (%s): %s'%(code, result))
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000219
220 def build_post_data(self, action):
221 # figure the data to send - the metadata plus some additional
222 # information used by the package server
223 meta = self.distribution.metadata
224 data = {
225 ':action': action,
226 'metadata_version' : '1.0',
227 'name': meta.get_name(),
228 'version': meta.get_version(),
229 'summary': meta.get_description(),
230 'home_page': meta.get_url(),
231 'author': meta.get_contact(),
232 'author_email': meta.get_contact_email(),
233 'license': meta.get_licence(),
234 'description': meta.get_long_description(),
235 'keywords': meta.get_keywords(),
236 'platform': meta.get_platforms(),
Andrew M. Kuchling23c98c52003-02-19 13:49:35 +0000237 'classifiers': meta.get_classifiers(),
Andrew M. Kuchling80be59b2003-02-19 14:27:21 +0000238 'download_url': meta.get_download_url(),
Fred Drakedb7b0022005-03-20 22:19:47 +0000239 # PEP 314
240 'provides': meta.get_provides(),
241 'requires': meta.get_requires(),
242 'obsoletes': meta.get_obsoletes(),
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000243 }
Fred Drakedb7b0022005-03-20 22:19:47 +0000244 if data['provides'] or data['requires'] or data['obsoletes']:
245 data['metadata_version'] = '1.1'
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000246 return data
247
248 def post_to_server(self, data, auth=None):
249 ''' Post a query to the server, and return a string response.
250 '''
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000251 self.announce('Registering %s to %s' % (data['name'],
252 self.repository), log.INFO)
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000253 # Build up the MIME payload for the urllib2 POST data
254 boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
255 sep_boundary = '\n--' + boundary
256 end_boundary = sep_boundary + '--'
Guido van Rossum34d19282007-08-09 01:03:29 +0000257 body = io.StringIO()
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000258 for key, value in data.items():
259 # handle multiple entries for the same name
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 if type(value) not in (type([]), type( () )):
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000261 value = [value]
262 for value in value:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000263 value = str(value).encode("utf-8")
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000264 body.write(sep_boundary)
265 body.write('\nContent-Disposition: form-data; name="%s"'%key)
266 body.write("\n\n")
267 body.write(value)
268 if value and value[-1] == '\r':
269 body.write('\n') # write an extra newline (lurve Macs)
270 body.write(end_boundary)
271 body.write("\n")
272 body = body.getvalue()
273
274 # build the Request
275 headers = {
Walter Dörwalda6e8a4a2005-03-31 13:57:38 +0000276 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary,
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000277 'Content-length': str(len(body))
278 }
279 req = urllib2.Request(self.repository, body, headers)
280
281 # handle HTTP and include the Basic Auth handler
282 opener = urllib2.build_opener(
283 urllib2.HTTPBasicAuthHandler(password_mgr=auth)
284 )
285 data = ''
286 try:
287 result = opener.open(req)
Guido van Rossumb940e112007-01-10 16:19:56 +0000288 except urllib2.HTTPError as e:
Andrew M. Kuchling23c98c52003-02-19 13:49:35 +0000289 if self.show_response:
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000290 data = e.fp.read()
291 result = e.code, e.msg
Guido van Rossumb940e112007-01-10 16:19:56 +0000292 except urllib2.URLError as e:
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000293 result = 500, str(e)
294 else:
Andrew M. Kuchling23c98c52003-02-19 13:49:35 +0000295 if self.show_response:
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000296 data = result.read()
297 result = 200, 'OK'
Andrew M. Kuchling23c98c52003-02-19 13:49:35 +0000298 if self.show_response:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000299 print('-'*75, data, '-'*75)
Andrew M. Kuchling51a6a4c2003-01-03 15:29:28 +0000300 return result