upload.py 7.1 KB

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