PageRenderTime 27ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/distutils/distutils/command/register.py

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