upload.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """
  2. distutils.command.upload
  3. Implements the Distutils 'upload' subcommand (upload package to a package
  4. index).
  5. """
  6. import os
  7. import io
  8. import hashlib
  9. from base64 import standard_b64encode
  10. from urllib.request import urlopen, Request, HTTPError
  11. from urllib.parse import urlparse
  12. from distutils.errors import DistutilsError, DistutilsOptionError
  13. from distutils.core import PyPIRCCommand
  14. from distutils.spawn import spawn
  15. from distutils import log
  16. # PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)
  17. # https://bugs.python.org/issue40698
  18. _FILE_CONTENT_DIGESTS = {
  19. "md5_digest": getattr(hashlib, "md5", None),
  20. "sha256_digest": getattr(hashlib, "sha256", None),
  21. "blake2_256_digest": getattr(hashlib, "blake2b", None),
  22. }
  23. class upload(PyPIRCCommand):
  24. description = "upload binary package to PyPI"
  25. user_options = PyPIRCCommand.user_options + [
  26. ('sign', 's',
  27. 'sign files to upload using gpg'),
  28. ('identity=', 'i', 'GPG identity used to sign files'),
  29. ]
  30. boolean_options = PyPIRCCommand.boolean_options + ['sign']
  31. def initialize_options(self):
  32. PyPIRCCommand.initialize_options(self)
  33. self.username = ''
  34. self.password = ''
  35. self.show_response = 0
  36. self.sign = False
  37. self.identity = None
  38. def finalize_options(self):
  39. PyPIRCCommand.finalize_options(self)
  40. if self.identity and not self.sign:
  41. raise DistutilsOptionError(
  42. "Must use --sign for --identity to have meaning"
  43. )
  44. config = self._read_pypirc()
  45. if config != {}:
  46. self.username = config['username']
  47. self.password = config['password']
  48. self.repository = config['repository']
  49. self.realm = config['realm']
  50. # getting the password from the distribution
  51. # if previously set by the register command
  52. if not self.password and self.distribution.password:
  53. self.password = self.distribution.password
  54. def run(self):
  55. if not self.distribution.dist_files:
  56. msg = ("Must create and upload files in one command "
  57. "(e.g. setup.py sdist upload)")
  58. raise DistutilsOptionError(msg)
  59. for command, pyversion, filename in self.distribution.dist_files:
  60. self.upload_file(command, pyversion, filename)
  61. def upload_file(self, command, pyversion, filename):
  62. # Makes sure the repository URL is compliant
  63. schema, netloc, url, params, query, fragments = \
  64. urlparse(self.repository)
  65. if params or query or fragments:
  66. raise AssertionError("Incompatible url %s" % self.repository)
  67. if schema not in ('http', 'https'):
  68. raise AssertionError("unsupported schema " + schema)
  69. # Sign if requested
  70. if self.sign:
  71. gpg_args = ["gpg", "--detach-sign", "-a", filename]
  72. if self.identity:
  73. gpg_args[2:2] = ["--local-user", self.identity]
  74. spawn(gpg_args,
  75. dry_run=self.dry_run)
  76. # Fill in the data - send all the meta-data in case we need to
  77. # register a new release
  78. f = open(filename,'rb')
  79. try:
  80. content = f.read()
  81. finally:
  82. f.close()
  83. meta = self.distribution.metadata
  84. data = {
  85. # action
  86. ':action': 'file_upload',
  87. 'protocol_version': '1',
  88. # identify release
  89. 'name': meta.get_name(),
  90. 'version': meta.get_version(),
  91. # file content
  92. 'content': (os.path.basename(filename),content),
  93. 'filetype': command,
  94. 'pyversion': pyversion,
  95. # additional meta-data
  96. 'metadata_version': '1.0',
  97. 'summary': meta.get_description(),
  98. 'home_page': meta.get_url(),
  99. 'author': meta.get_contact(),
  100. 'author_email': meta.get_contact_email(),
  101. 'license': meta.get_licence(),
  102. 'description': meta.get_long_description(),
  103. 'keywords': meta.get_keywords(),
  104. 'platform': meta.get_platforms(),
  105. 'classifiers': meta.get_classifiers(),
  106. 'download_url': meta.get_download_url(),
  107. # PEP 314
  108. 'provides': meta.get_provides(),
  109. 'requires': meta.get_requires(),
  110. 'obsoletes': meta.get_obsoletes(),
  111. }
  112. data['comment'] = ''
  113. # file content digests
  114. for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():
  115. if digest_cons is None:
  116. continue
  117. try:
  118. data[digest_name] = digest_cons(content).hexdigest()
  119. except ValueError:
  120. # hash digest not available or blocked by security policy
  121. pass
  122. if self.sign:
  123. with open(filename + ".asc", "rb") as f:
  124. data['gpg_signature'] = (os.path.basename(filename) + ".asc",
  125. f.read())
  126. # set up the authentication
  127. user_pass = (self.username + ":" + self.password).encode('ascii')
  128. # The exact encoding of the authentication string is debated.
  129. # Anyway PyPI only accepts ascii for both username or password.
  130. auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
  131. # Build up the MIME payload for the POST data
  132. boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
  133. sep_boundary = b'\r\n--' + boundary.encode('ascii')
  134. end_boundary = sep_boundary + b'--\r\n'
  135. body = io.BytesIO()
  136. for key, value in data.items():
  137. title = '\r\nContent-Disposition: form-data; name="%s"' % key
  138. # handle multiple entries for the same name
  139. if not isinstance(value, list):
  140. value = [value]
  141. for value in value:
  142. if type(value) is tuple:
  143. title += '; filename="%s"' % value[0]
  144. value = value[1]
  145. else:
  146. value = str(value).encode('utf-8')
  147. body.write(sep_boundary)
  148. body.write(title.encode('utf-8'))
  149. body.write(b"\r\n\r\n")
  150. body.write(value)
  151. body.write(end_boundary)
  152. body = body.getvalue()
  153. msg = "Submitting %s to %s" % (filename, self.repository)
  154. self.announce(msg, log.INFO)
  155. # build the Request
  156. headers = {
  157. 'Content-type': 'multipart/form-data; boundary=%s' % boundary,
  158. 'Content-length': str(len(body)),
  159. 'Authorization': auth,
  160. }
  161. request = Request(self.repository, data=body,
  162. headers=headers)
  163. # send the data
  164. try:
  165. result = urlopen(request)
  166. status = result.getcode()
  167. reason = result.msg
  168. except HTTPError as e:
  169. status = e.code
  170. reason = e.msg
  171. except OSError as e:
  172. self.announce(str(e), log.ERROR)
  173. raise
  174. if status == 200:
  175. self.announce('Server response (%s): %s' % (status, reason),
  176. log.INFO)
  177. if self.show_response:
  178. text = self._read_pypi_response(result)
  179. msg = '\n'.join(('-' * 75, text, '-' * 75))
  180. self.announce(msg, log.INFO)
  181. else:
  182. msg = 'Upload failed (%s): %s' % (status, reason)
  183. self.announce(msg, log.ERROR)
  184. raise DistutilsError(msg)