upload_docs.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. """upload_docs
  2. Implements a Distutils 'upload_docs' subcommand (upload documentation to
  3. sites other than PyPi such as devpi).
  4. """
  5. from base64 import standard_b64encode
  6. from distutils import log
  7. from distutils.errors import DistutilsOptionError
  8. import os
  9. import socket
  10. import zipfile
  11. import tempfile
  12. import shutil
  13. import itertools
  14. import functools
  15. import http.client
  16. import urllib.parse
  17. from .._importlib import metadata
  18. from ..warnings import SetuptoolsDeprecationWarning
  19. from .upload import upload
  20. def _encode(s):
  21. return s.encode('utf-8', 'surrogateescape')
  22. class upload_docs(upload):
  23. # override the default repository as upload_docs isn't
  24. # supported by Warehouse (and won't be).
  25. DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
  26. description = 'Upload documentation to sites other than PyPi such as devpi'
  27. user_options = [
  28. (
  29. 'repository=',
  30. 'r',
  31. "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY,
  32. ),
  33. ('show-response', None, 'display full response text from server'),
  34. ('upload-dir=', None, 'directory to upload'),
  35. ]
  36. boolean_options = upload.boolean_options
  37. def has_sphinx(self):
  38. return bool(
  39. self.upload_dir is None
  40. and metadata.entry_points(group='distutils.commands', name='build_sphinx')
  41. )
  42. sub_commands = [('build_sphinx', has_sphinx)]
  43. def initialize_options(self):
  44. upload.initialize_options(self)
  45. self.upload_dir = None
  46. self.target_dir = None
  47. def finalize_options(self):
  48. log.warn(
  49. "Upload_docs command is deprecated. Use Read the Docs "
  50. "(https://readthedocs.org) instead."
  51. )
  52. upload.finalize_options(self)
  53. if self.upload_dir is None:
  54. if self.has_sphinx():
  55. build_sphinx = self.get_finalized_command('build_sphinx')
  56. self.target_dir = dict(build_sphinx.builder_target_dirs)['html']
  57. else:
  58. build = self.get_finalized_command('build')
  59. self.target_dir = os.path.join(build.build_base, 'docs')
  60. else:
  61. self.ensure_dirname('upload_dir')
  62. self.target_dir = self.upload_dir
  63. self.announce('Using upload directory %s' % self.target_dir)
  64. def create_zipfile(self, filename):
  65. zip_file = zipfile.ZipFile(filename, "w")
  66. try:
  67. self.mkpath(self.target_dir) # just in case
  68. for root, dirs, files in os.walk(self.target_dir):
  69. if root == self.target_dir and not files:
  70. tmpl = "no files found in upload directory '%s'"
  71. raise DistutilsOptionError(tmpl % self.target_dir)
  72. for name in files:
  73. full = os.path.join(root, name)
  74. relative = root[len(self.target_dir) :].lstrip(os.path.sep)
  75. dest = os.path.join(relative, name)
  76. zip_file.write(full, dest)
  77. finally:
  78. zip_file.close()
  79. def run(self):
  80. SetuptoolsDeprecationWarning.emit(
  81. "Deprecated command",
  82. """
  83. upload_docs is deprecated and will be removed in a future version.
  84. Instead, use tools like devpi and Read the Docs; or lower level tools like
  85. httpie and curl to interact directly with your hosting service API.
  86. """,
  87. due_date=(2023, 9, 26), # warning introduced in 27 Jul 2022
  88. )
  89. # Run sub commands
  90. for cmd_name in self.get_sub_commands():
  91. self.run_command(cmd_name)
  92. tmp_dir = tempfile.mkdtemp()
  93. name = self.distribution.metadata.get_name()
  94. zip_file = os.path.join(tmp_dir, "%s.zip" % name)
  95. try:
  96. self.create_zipfile(zip_file)
  97. self.upload_file(zip_file)
  98. finally:
  99. shutil.rmtree(tmp_dir)
  100. @staticmethod
  101. def _build_part(item, sep_boundary):
  102. key, values = item
  103. title = '\nContent-Disposition: form-data; name="%s"' % key
  104. # handle multiple entries for the same name
  105. if not isinstance(values, list):
  106. values = [values]
  107. for value in values:
  108. if isinstance(value, tuple):
  109. title += '; filename="%s"' % value[0]
  110. value = value[1]
  111. else:
  112. value = _encode(value)
  113. yield sep_boundary
  114. yield _encode(title)
  115. yield b"\n\n"
  116. yield value
  117. if value and value[-1:] == b'\r':
  118. yield b'\n' # write an extra newline (lurve Macs)
  119. @classmethod
  120. def _build_multipart(cls, data):
  121. """
  122. Build up the MIME payload for the POST data
  123. """
  124. boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
  125. sep_boundary = b'\n--' + boundary.encode('ascii')
  126. end_boundary = sep_boundary + b'--'
  127. end_items = (
  128. end_boundary,
  129. b"\n",
  130. )
  131. builder = functools.partial(
  132. cls._build_part,
  133. sep_boundary=sep_boundary,
  134. )
  135. part_groups = map(builder, data.items())
  136. parts = itertools.chain.from_iterable(part_groups)
  137. body_items = itertools.chain(parts, end_items)
  138. content_type = 'multipart/form-data; boundary=%s' % boundary
  139. return b''.join(body_items), content_type
  140. def upload_file(self, filename):
  141. with open(filename, 'rb') as f:
  142. content = f.read()
  143. meta = self.distribution.metadata
  144. data = {
  145. ':action': 'doc_upload',
  146. 'name': meta.get_name(),
  147. 'content': (os.path.basename(filename), content),
  148. }
  149. # set up the authentication
  150. credentials = _encode(self.username + ':' + self.password)
  151. credentials = standard_b64encode(credentials).decode('ascii')
  152. auth = "Basic " + credentials
  153. body, ct = self._build_multipart(data)
  154. msg = "Submitting documentation to %s" % (self.repository)
  155. self.announce(msg, log.INFO)
  156. # build the Request
  157. # We can't use urllib2 since we need to send the Basic
  158. # auth right with the first request
  159. schema, netloc, url, params, query, fragments = urllib.parse.urlparse(
  160. self.repository
  161. )
  162. assert not params and not query and not fragments
  163. if schema == 'http':
  164. conn = http.client.HTTPConnection(netloc)
  165. elif schema == 'https':
  166. conn = http.client.HTTPSConnection(netloc)
  167. else:
  168. raise AssertionError("unsupported schema " + schema)
  169. data = ''
  170. try:
  171. conn.connect()
  172. conn.putrequest("POST", url)
  173. content_type = ct
  174. conn.putheader('Content-type', content_type)
  175. conn.putheader('Content-length', str(len(body)))
  176. conn.putheader('Authorization', auth)
  177. conn.endheaders()
  178. conn.send(body)
  179. except socket.error as e:
  180. self.announce(str(e), log.ERROR)
  181. return
  182. r = conn.getresponse()
  183. if r.status == 200:
  184. msg = 'Server response (%s): %s' % (r.status, r.reason)
  185. self.announce(msg, log.INFO)
  186. elif r.status == 301:
  187. location = r.getheader('Location')
  188. if location is None:
  189. location = 'https://pythonhosted.org/%s/' % meta.get_name()
  190. msg = 'Upload successful. Visit %s' % location
  191. self.announce(msg, log.INFO)
  192. else:
  193. msg = 'Upload failed (%s): %s' % (r.status, r.reason)
  194. self.announce(msg, log.ERROR)
  195. if self.show_response:
  196. print('-' * 75, r.read(), '-' * 75)