1 """distutils.command.register
3 Implements the Distutils 'register' command (register with the repository).
6 # created 2002/10/21, Richard Jones
10 import sys
, os
, string
, urllib2
, getpass
, urlparse
11 import StringIO
, ConfigParser
13 from distutils
.core
import Command
14 from distutils
.errors
import *
16 class register(Command
):
18 description
= "register the distribution with the repository"
20 # XXX must update this to python.org before 2.3final!
21 DEFAULT_REPOSITORY
= 'http://www.amk.ca/cgi-bin/pypi.cgi'
25 "url of repository [default: %s]"%DEFAULT_REPOSITORY
),
27 'verify the package metadata for correctness'),
28 ('list-classifiers', None,
29 'list the valid Trove classifiers'),
31 'display full response from server'),
33 boolean_options
= ['verify', 'verbose', 'list-classifiers']
35 def initialize_options(self
):
36 self
.repository
= None
39 self
.list_classifiers
= 0
41 def finalize_options(self
):
42 if self
.repository
is None:
43 self
.repository
= self
.DEFAULT_REPOSITORY
48 self
.verify_metadata()
49 elif self
.list_classifiers
:
54 def check_metadata(self
):
55 """Ensure that all required elements of meta-data (name, version,
56 URL, (author and author_email) or (maintainer and
57 maintainer_email)) are supplied by the Distribution object; warn if
60 metadata
= self
.distribution
.metadata
63 for attr
in ('name', 'version', 'url'):
64 if not (hasattr(metadata
, attr
) and getattr(metadata
, attr
)):
68 self
.warn("missing required meta-data: " +
69 string
.join(missing
, ", "))
72 if not metadata
.author_email
:
73 self
.warn("missing meta-data: if 'author' supplied, " +
74 "'author_email' must be supplied too")
75 elif metadata
.maintainer
:
76 if not metadata
.maintainer_email
:
77 self
.warn("missing meta-data: if 'maintainer' supplied, " +
78 "'maintainer_email' must be supplied too")
80 self
.warn("missing meta-data: either (author and author_email) " +
81 "or (maintainer and maintainer_email) " +
84 def classifiers(self
):
85 ''' Fetch the list of classifiers from the server.
87 response
= urllib2
.urlopen(self
.repository
+'?:action=list_classifiers')
90 def verify_metadata(self
):
91 ''' Send the metadata to the package index server to be checked.
93 # send the info to the server and report the result
94 (code
, result
) = self
.post_to_server(self
.build_post_data('verify'))
95 print 'Server response (%s): %s'%(code
, result
)
97 def send_metadata(self
):
98 ''' Send the metadata to the package index server.
100 Well, do the following:
101 1. figure who the user is, and then
102 2. send the data as a Basic auth'ed POST.
104 First we try to read the username/password from $HOME/.pypirc,
105 which is a ConfigParser-formatted file with a section
106 [server-login] containing username and password entries (both
113 Otherwise, to figure who the user is, we offer the user three
116 1. use existing login,
117 2. register as a new user, or
118 3. set the password to a random string and email the user.
122 username
= password
= ''
124 # see if we can short-cut and get the username/password from the
127 if os
.environ
.has_key('HOME'):
128 rc
= os
.path
.join(os
.environ
['HOME'], '.pypirc')
129 if os
.path
.exists(rc
):
130 print 'Using PyPI login from %s'%rc
131 config
= ConfigParser
.ConfigParser()
133 username
= config
.get('server-login', 'username')
134 password
= config
.get('server-login', 'password')
137 # get the user's login info
138 choices
= '1 2 3 4'.split()
139 while choice
not in choices
:
140 print '''We need to know who you are, so please choose either:
141 1. use your existing login,
142 2. register as a new user,
143 3. have the server generate a new password for you (and email it to you), or
145 Your selection [default 1]: ''',
149 elif choice
not in choices
:
150 print 'Please choose one of the four options!'
153 # get the username and password
155 username
= raw_input('Username: ')
157 password
= getpass
.getpass('Password: ')
159 # set up the authentication
160 auth
= urllib2
.HTTPPasswordMgr()
161 host
= urlparse
.urlparse(self
.repository
)[1]
162 auth
.add_password('pypi', host
, username
, password
)
164 # send the info to the server and report the result
165 code
, result
= self
.post_to_server(self
.build_post_data('submit'),
167 print 'Server response (%s): %s'%(code
, result
)
169 # possibly save the login
170 if os
.environ
.has_key('HOME') and config
is None and code
== 200:
171 rc
= os
.path
.join(os
.environ
['HOME'], '.pypirc')
172 print 'I can store your PyPI login so future submissions will be faster.'
173 print '(the login will be stored in %s)'%rc
175 while choice
.lower() not in 'yn':
176 choice
= raw_input('Save your login (y/N)?')
179 if choice
.lower() == 'y':
181 f
.write('[server-login]\nusername:%s\npassword:%s\n'%(
189 data
= {':action': 'user'}
190 data
['name'] = data
['password'] = data
['email'] = ''
191 data
['confirm'] = None
192 while not data
['name']:
193 data
['name'] = raw_input('Username: ')
194 while data
['password'] != data
['confirm']:
195 while not data
['password']:
196 data
['password'] = getpass
.getpass('Password: ')
197 while not data
['confirm']:
198 data
['confirm'] = getpass
.getpass(' Confirm: ')
199 if data
['password'] != data
['confirm']:
200 data
['password'] = ''
201 data
['confirm'] = None
202 print "Password and confirm don't match!"
203 while not data
['email']:
204 data
['email'] = raw_input(' EMail: ')
205 code
, result
= self
.post_to_server(data
)
207 print 'Server response (%s): %s'%(code
, result
)
209 print 'You will receive an email shortly.'
210 print 'Follow the instructions in it to complete registration.'
212 data
= {':action': 'password_reset'}
214 while not data
['email']:
215 data
['email'] = raw_input('Your email address: ')
216 code
, result
= self
.post_to_server(data
)
217 print 'Server response (%s): %s'%(code
, result
)
219 def build_post_data(self
, action
):
220 # figure the data to send - the metadata plus some additional
221 # information used by the package server
222 meta
= self
.distribution
.metadata
225 'metadata_version' : '1.0',
226 'name': meta
.get_name(),
227 'version': meta
.get_version(),
228 'summary': meta
.get_description(),
229 'home_page': meta
.get_url(),
230 'author': meta
.get_contact(),
231 'author_email': meta
.get_contact_email(),
232 'license': meta
.get_licence(),
233 'description': meta
.get_long_description(),
234 'keywords': meta
.get_keywords(),
235 'platform': meta
.get_platforms(),
237 if hasattr(meta
, 'classifiers'):
238 data
['classifiers'] = meta
.get_classifiers()
241 def post_to_server(self
, data
, auth
=None):
242 ''' Post a query to the server, and return a string response.
245 # Build up the MIME payload for the urllib2 POST data
246 boundary
= '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
247 sep_boundary
= '\n--' + boundary
248 end_boundary
= sep_boundary
+ '--'
249 body
= StringIO
.StringIO()
250 for key
, value
in data
.items():
251 # handle multiple entries for the same name
252 if type(value
) != type([]):
256 body
.write(sep_boundary
)
257 body
.write('\nContent-Disposition: form-data; name="%s"'%key
)
260 if value
and value
[-1] == '\r':
261 body
.write('\n') # write an extra newline (lurve Macs)
262 body
.write(end_boundary
)
264 body
= body
.getvalue()
268 'Content-type': 'multipart/form-data; boundary=%s'%boundary
,
269 'Content-length': str(len(body
))
271 req
= urllib2
.Request(self
.repository
, body
, headers
)
273 # handle HTTP and include the Basic Auth handler
274 opener
= urllib2
.build_opener(
275 urllib2
.HTTPBasicAuthHandler(password_mgr
=auth
)
279 result
= opener
.open(req
)
280 except urllib2
.HTTPError
, e
:
283 result
= e
.code
, e
.msg
284 except urllib2
.URLError
, e
:
291 print '-'*75, data
, '-'*75