PageRenderTime 40ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/distutils/command/register.py

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