upload_docs.py 7.0 KB

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