upload_docs.py 6.9 KB

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