/Lib/distutils/command/register.py

http://unladen-swallow.googlecode.com/ · Python · 301 lines · 265 code · 12 blank · 24 comment · 41 complexity · ca87da90b9f003c1213b87c1f0399892 MD5 · raw file

  1. """distutils.command.register
  2. Implements the Distutils 'register' command (register with the repository).
  3. """
  4. # created 2002/10/21, Richard Jones
  5. __revision__ = "$Id: register.py 67944 2008-12-27 13:28:42Z tarek.ziade $"
  6. import os, string, urllib2, getpass, urlparse
  7. import StringIO
  8. from distutils.core import PyPIRCCommand
  9. from distutils.errors import *
  10. from distutils import log
  11. class register(PyPIRCCommand):
  12. description = ("register the distribution with the Python package index")
  13. user_options = PyPIRCCommand.user_options + [
  14. ('list-classifiers', None,
  15. 'list the valid Trove classifiers'),
  16. ]
  17. boolean_options = PyPIRCCommand.boolean_options + [
  18. 'verify', 'list-classifiers']
  19. def initialize_options(self):
  20. PyPIRCCommand.initialize_options(self)
  21. self.list_classifiers = 0
  22. def run(self):
  23. self.finalize_options()
  24. self._set_config()
  25. self.check_metadata()
  26. if self.dry_run:
  27. self.verify_metadata()
  28. elif self.list_classifiers:
  29. self.classifiers()
  30. else:
  31. self.send_metadata()
  32. def check_metadata(self):
  33. """Ensure that all required elements of meta-data (name, version,
  34. URL, (author and author_email) or (maintainer and
  35. maintainer_email)) are supplied by the Distribution object; warn if
  36. any are missing.
  37. """
  38. metadata = self.distribution.metadata
  39. missing = []
  40. for attr in ('name', 'version', 'url'):
  41. if not (hasattr(metadata, attr) and getattr(metadata, attr)):
  42. missing.append(attr)
  43. if missing:
  44. self.warn("missing required meta-data: " +
  45. string.join(missing, ", "))
  46. if metadata.author:
  47. if not metadata.author_email:
  48. self.warn("missing meta-data: if 'author' supplied, " +
  49. "'author_email' must be supplied too")
  50. elif metadata.maintainer:
  51. if not metadata.maintainer_email:
  52. self.warn("missing meta-data: if 'maintainer' supplied, " +
  53. "'maintainer_email' must be supplied too")
  54. else:
  55. self.warn("missing meta-data: either (author and author_email) " +
  56. "or (maintainer and maintainer_email) " +
  57. "must be supplied")
  58. def _set_config(self):
  59. ''' Reads the configuration file and set attributes.
  60. '''
  61. config = self._read_pypirc()
  62. if config != {}:
  63. self.username = config['username']
  64. self.password = config['password']
  65. self.repository = config['repository']
  66. self.realm = config['realm']
  67. self.has_config = True
  68. else:
  69. if self.repository not in ('pypi', self.DEFAULT_REPOSITORY):
  70. raise ValueError('%s not found in .pypirc' % self.repository)
  71. if self.repository == 'pypi':
  72. self.repository = self.DEFAULT_REPOSITORY
  73. self.has_config = False
  74. def classifiers(self):
  75. ''' Fetch the list of classifiers from the server.
  76. '''
  77. response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
  78. print response.read()
  79. def verify_metadata(self):
  80. ''' Send the metadata to the package index server to be checked.
  81. '''
  82. # send the info to the server and report the result
  83. (code, result) = self.post_to_server(self.build_post_data('verify'))
  84. print 'Server response (%s): %s'%(code, result)
  85. def send_metadata(self):
  86. ''' Send the metadata to the package index server.
  87. Well, do the following:
  88. 1. figure who the user is, and then
  89. 2. send the data as a Basic auth'ed POST.
  90. First we try to read the username/password from $HOME/.pypirc,
  91. which is a ConfigParser-formatted file with a section
  92. [distutils] containing username and password entries (both
  93. in clear text). Eg:
  94. [distutils]
  95. index-servers =
  96. pypi
  97. [pypi]
  98. username: fred
  99. password: sekrit
  100. Otherwise, to figure who the user is, we offer the user three
  101. choices:
  102. 1. use existing login,
  103. 2. register as a new user, or
  104. 3. set the password to a random string and email the user.
  105. '''
  106. # see if we can short-cut and get the username/password from the
  107. # config
  108. if self.has_config:
  109. choice = '1'
  110. username = self.username
  111. password = self.password
  112. else:
  113. choice = 'x'
  114. username = password = ''
  115. # get the user's login info
  116. choices = '1 2 3 4'.split()
  117. while choice not in choices:
  118. self.announce('''\
  119. We need to know who you are, so please choose either:
  120. 1. use your existing login,
  121. 2. register as a new user,
  122. 3. have the server generate a new password for you (and email it to you), or
  123. 4. quit
  124. Your selection [default 1]: ''', log.INFO)
  125. choice = raw_input()
  126. if not choice:
  127. choice = '1'
  128. elif choice not in choices:
  129. print 'Please choose one of the four options!'
  130. if choice == '1':
  131. # get the username and password
  132. while not username:
  133. username = raw_input('Username: ')
  134. while not password:
  135. password = getpass.getpass('Password: ')
  136. # set up the authentication
  137. auth = urllib2.HTTPPasswordMgr()
  138. host = urlparse.urlparse(self.repository)[1]
  139. auth.add_password(self.realm, host, username, password)
  140. # send the info to the server and report the result
  141. code, result = self.post_to_server(self.build_post_data('submit'),
  142. auth)
  143. self.announce('Server response (%s): %s' % (code, result),
  144. log.INFO)
  145. # possibly save the login
  146. if not self.has_config and code == 200:
  147. self.announce(('I can store your PyPI login so future '
  148. 'submissions will be faster.'), log.INFO)
  149. self.announce('(the login will be stored in %s)' % \
  150. self._get_rc_file(), log.INFO)
  151. choice = 'X'
  152. while choice.lower() not in 'yn':
  153. choice = raw_input('Save your login (y/N)?')
  154. if not choice:
  155. choice = 'n'
  156. if choice.lower() == 'y':
  157. self._store_pypirc(username, password)
  158. elif choice == '2':
  159. data = {':action': 'user'}
  160. data['name'] = data['password'] = data['email'] = ''
  161. data['confirm'] = None
  162. while not data['name']:
  163. data['name'] = raw_input('Username: ')
  164. while data['password'] != data['confirm']:
  165. while not data['password']:
  166. data['password'] = getpass.getpass('Password: ')
  167. while not data['confirm']:
  168. data['confirm'] = getpass.getpass(' Confirm: ')
  169. if data['password'] != data['confirm']:
  170. data['password'] = ''
  171. data['confirm'] = None
  172. print "Password and confirm don't match!"
  173. while not data['email']:
  174. data['email'] = raw_input(' EMail: ')
  175. code, result = self.post_to_server(data)
  176. if code != 200:
  177. print 'Server response (%s): %s'%(code, result)
  178. else:
  179. print 'You will receive an email shortly.'
  180. print 'Follow the instructions in it to complete registration.'
  181. elif choice == '3':
  182. data = {':action': 'password_reset'}
  183. data['email'] = ''
  184. while not data['email']:
  185. data['email'] = raw_input('Your email address: ')
  186. code, result = self.post_to_server(data)
  187. print 'Server response (%s): %s'%(code, result)
  188. def build_post_data(self, action):
  189. # figure the data to send - the metadata plus some additional
  190. # information used by the package server
  191. meta = self.distribution.metadata
  192. data = {
  193. ':action': action,
  194. 'metadata_version' : '1.0',
  195. 'name': meta.get_name(),
  196. 'version': meta.get_version(),
  197. 'summary': meta.get_description(),
  198. 'home_page': meta.get_url(),
  199. 'author': meta.get_contact(),
  200. 'author_email': meta.get_contact_email(),
  201. 'license': meta.get_licence(),
  202. 'description': meta.get_long_description(),
  203. 'keywords': meta.get_keywords(),
  204. 'platform': meta.get_platforms(),
  205. 'classifiers': meta.get_classifiers(),
  206. 'download_url': meta.get_download_url(),
  207. # PEP 314
  208. 'provides': meta.get_provides(),
  209. 'requires': meta.get_requires(),
  210. 'obsoletes': meta.get_obsoletes(),
  211. }
  212. if data['provides'] or data['requires'] or data['obsoletes']:
  213. data['metadata_version'] = '1.1'
  214. return data
  215. def post_to_server(self, data, auth=None):
  216. ''' Post a query to the server, and return a string response.
  217. '''
  218. self.announce('Registering %s to %s' % (data['name'],
  219. self.repository), log.INFO)
  220. # Build up the MIME payload for the urllib2 POST data
  221. boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
  222. sep_boundary = '\n--' + boundary
  223. end_boundary = sep_boundary + '--'
  224. body = StringIO.StringIO()
  225. for key, value in data.items():
  226. # handle multiple entries for the same name
  227. if type(value) not in (type([]), type( () )):
  228. value = [value]
  229. for value in value:
  230. value = unicode(value).encode("utf-8")
  231. body.write(sep_boundary)
  232. body.write('\nContent-Disposition: form-data; name="%s"'%key)
  233. body.write("\n\n")
  234. body.write(value)
  235. if value and value[-1] == '\r':
  236. body.write('\n') # write an extra newline (lurve Macs)
  237. body.write(end_boundary)
  238. body.write("\n")
  239. body = body.getvalue()
  240. # build the Request
  241. headers = {
  242. 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary,
  243. 'Content-length': str(len(body))
  244. }
  245. req = urllib2.Request(self.repository, body, headers)
  246. # handle HTTP and include the Basic Auth handler
  247. opener = urllib2.build_opener(
  248. urllib2.HTTPBasicAuthHandler(password_mgr=auth)
  249. )
  250. data = ''
  251. try:
  252. result = opener.open(req)
  253. except urllib2.HTTPError, e:
  254. if self.show_response:
  255. data = e.fp.read()
  256. result = e.code, e.msg
  257. except urllib2.URLError, e:
  258. result = 500, str(e)
  259. else:
  260. if self.show_response:
  261. data = result.read()
  262. result = 200, 'OK'
  263. if self.show_response:
  264. print '-'*75, data, '-'*75
  265. return result