PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/distutils/command/register.py

https://gitlab.com/abhi1tb/build
Python | 304 lines | 291 code | 6 blank | 7 comment | 7 complexity | 6b2ba18226e1e6c6c5b3b0e3c2f4c09d 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. import getpass
  6. import io
  7. import urllib.parse, urllib.request
  8. from warnings import warn
  9. from distutils.core import PyPIRCCommand
  10. from distutils.errors import *
  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. url = self.repository+'?:action=list_classifiers'
  74. response = urllib.request.urlopen(url)
  75. log.info(self._read_pypi_response(response))
  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 = 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 = input('Username: ')
  131. while not password:
  132. password = getpass.getpass('Password: ')
  133. # set up the authentication
  134. auth = urllib.request.HTTPPasswordMgr()
  135. host = urllib.parse.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 = 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'] = 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'] = 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'] = 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 = io.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. value = str(value)
  236. body.write(sep_boundary)
  237. body.write('\nContent-Disposition: form-data; name="%s"'%key)
  238. body.write("\n\n")
  239. body.write(value)
  240. if value and value[-1] == '\r':
  241. body.write('\n') # write an extra newline (lurve Macs)
  242. body.write(end_boundary)
  243. body.write("\n")
  244. body = body.getvalue().encode("utf-8")
  245. # build the Request
  246. headers = {
  247. 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary,
  248. 'Content-length': str(len(body))
  249. }
  250. req = urllib.request.Request(self.repository, body, headers)
  251. # handle HTTP and include the Basic Auth handler
  252. opener = urllib.request.build_opener(
  253. urllib.request.HTTPBasicAuthHandler(password_mgr=auth)
  254. )
  255. data = ''
  256. try:
  257. result = opener.open(req)
  258. except urllib.error.HTTPError as e:
  259. if self.show_response:
  260. data = e.fp.read()
  261. result = e.code, e.msg
  262. except urllib.error.URLError as e:
  263. result = 500, str(e)
  264. else:
  265. if self.show_response:
  266. data = self._read_pypi_response(result)
  267. result = 200, 'OK'
  268. if self.show_response:
  269. msg = '\n'.join(('-' * 75, data, '-' * 75))
  270. self.announce(msg, log.INFO)
  271. return result