ez_setup.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python
  2. """Bootstrap setuptools installation
  3. To use setuptools in your package's setup.py, include this
  4. file in the same directory and add this to the top of your setup.py::
  5. from ez_setup import use_setuptools
  6. use_setuptools()
  7. To require a specific version of setuptools, set a download
  8. mirror, or use an alternate download directory, simply supply
  9. the appropriate options to ``use_setuptools()``.
  10. This file can also be run as a script to install or upgrade setuptools.
  11. """
  12. import os
  13. import shutil
  14. import sys
  15. import tempfile
  16. import zipfile
  17. import optparse
  18. import subprocess
  19. import platform
  20. import textwrap
  21. import contextlib
  22. from distutils import log
  23. try:
  24. from urllib.request import urlopen
  25. except ImportError:
  26. from urllib2 import urlopen
  27. try:
  28. from site import USER_SITE
  29. except ImportError:
  30. USER_SITE = None
  31. DEFAULT_VERSION = "11.3.1"
  32. DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
  33. def _python_cmd(*args):
  34. """
  35. Return True if the command succeeded.
  36. """
  37. args = (sys.executable,) + args
  38. return subprocess.call(args) == 0
  39. def _install(archive_filename, install_args=()):
  40. with archive_context(archive_filename):
  41. # installing
  42. log.warn('Installing Setuptools')
  43. if not _python_cmd('setup.py', 'install', *install_args):
  44. log.warn('Something went wrong during the installation.')
  45. log.warn('See the error message above.')
  46. # exitcode will be 2
  47. return 2
  48. def _build_egg(egg, archive_filename, to_dir):
  49. with archive_context(archive_filename):
  50. # building an egg
  51. log.warn('Building a Setuptools egg in %s', to_dir)
  52. _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
  53. # returning the result
  54. log.warn(egg)
  55. if not os.path.exists(egg):
  56. raise IOError('Could not build the egg.')
  57. class ContextualZipFile(zipfile.ZipFile):
  58. """
  59. Supplement ZipFile class to support context manager for Python 2.6
  60. """
  61. def __enter__(self):
  62. return self
  63. def __exit__(self, type, value, traceback):
  64. self.close()
  65. def __new__(cls, *args, **kwargs):
  66. """
  67. Construct a ZipFile or ContextualZipFile as appropriate
  68. """
  69. if hasattr(zipfile.ZipFile, '__exit__'):
  70. return zipfile.ZipFile(*args, **kwargs)
  71. return super(ContextualZipFile, cls).__new__(cls)
  72. @contextlib.contextmanager
  73. def archive_context(filename):
  74. # extracting the archive
  75. tmpdir = tempfile.mkdtemp()
  76. log.warn('Extracting in %s', tmpdir)
  77. old_wd = os.getcwd()
  78. try:
  79. os.chdir(tmpdir)
  80. with ContextualZipFile(filename) as archive:
  81. archive.extractall()
  82. # going in the directory
  83. subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
  84. os.chdir(subdir)
  85. log.warn('Now working in %s', subdir)
  86. yield
  87. finally:
  88. os.chdir(old_wd)
  89. shutil.rmtree(tmpdir)
  90. def _do_download(version, download_base, to_dir, download_delay):
  91. egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
  92. % (version, sys.version_info[0], sys.version_info[1]))
  93. if not os.path.exists(egg):
  94. archive = download_setuptools(version, download_base,
  95. to_dir, download_delay)
  96. _build_egg(egg, archive, to_dir)
  97. sys.path.insert(0, egg)
  98. # Remove previously-imported pkg_resources if present (see
  99. # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
  100. if 'pkg_resources' in sys.modules:
  101. del sys.modules['pkg_resources']
  102. import setuptools
  103. setuptools.bootstrap_install_from = egg
  104. def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  105. to_dir=os.curdir, download_delay=15):
  106. to_dir = os.path.abspath(to_dir)
  107. rep_modules = 'pkg_resources', 'setuptools'
  108. imported = set(sys.modules).intersection(rep_modules)
  109. try:
  110. import pkg_resources
  111. except ImportError:
  112. return _do_download(version, download_base, to_dir, download_delay)
  113. try:
  114. pkg_resources.require("setuptools>=" + version)
  115. return
  116. except pkg_resources.DistributionNotFound:
  117. return _do_download(version, download_base, to_dir, download_delay)
  118. except pkg_resources.VersionConflict as VC_err:
  119. if imported:
  120. msg = textwrap.dedent("""
  121. The required version of setuptools (>={version}) is not available,
  122. and can't be installed while this script is running. Please
  123. install a more recent version first, using
  124. 'easy_install -U setuptools'.
  125. (Currently using {VC_err.args[0]!r})
  126. """).format(VC_err=VC_err, version=version)
  127. sys.stderr.write(msg)
  128. sys.exit(2)
  129. # otherwise, reload ok
  130. del pkg_resources, sys.modules['pkg_resources']
  131. return _do_download(version, download_base, to_dir, download_delay)
  132. def _clean_check(cmd, target):
  133. """
  134. Run the command to download target. If the command fails, clean up before
  135. re-raising the error.
  136. """
  137. try:
  138. subprocess.check_call(cmd)
  139. except subprocess.CalledProcessError:
  140. if os.access(target, os.F_OK):
  141. os.unlink(target)
  142. raise
  143. def download_file_powershell(url, target):
  144. """
  145. Download the file at url to target using Powershell (which will validate
  146. trust). Raise an exception if the command cannot complete.
  147. """
  148. target = os.path.abspath(target)
  149. ps_cmd = (
  150. "[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
  151. "[System.Net.CredentialCache]::DefaultCredentials; "
  152. "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
  153. % vars()
  154. )
  155. cmd = [
  156. 'powershell',
  157. '-Command',
  158. ps_cmd,
  159. ]
  160. _clean_check(cmd, target)
  161. def has_powershell():
  162. if platform.system() != 'Windows':
  163. return False
  164. cmd = ['powershell', '-Command', 'echo test']
  165. with open(os.path.devnull, 'wb') as devnull:
  166. try:
  167. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  168. except Exception:
  169. return False
  170. return True
  171. download_file_powershell.viable = has_powershell
  172. def download_file_curl(url, target):
  173. cmd = ['curl', url, '--silent', '--output', target]
  174. _clean_check(cmd, target)
  175. def has_curl():
  176. cmd = ['curl', '--version']
  177. with open(os.path.devnull, 'wb') as devnull:
  178. try:
  179. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  180. except Exception:
  181. return False
  182. return True
  183. download_file_curl.viable = has_curl
  184. def download_file_wget(url, target):
  185. cmd = ['wget', url, '--quiet', '--output-document', target]
  186. _clean_check(cmd, target)
  187. def has_wget():
  188. cmd = ['wget', '--version']
  189. with open(os.path.devnull, 'wb') as devnull:
  190. try:
  191. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  192. except Exception:
  193. return False
  194. return True
  195. download_file_wget.viable = has_wget
  196. def download_file_insecure(url, target):
  197. """
  198. Use Python to download the file, even though it cannot authenticate the
  199. connection.
  200. """
  201. src = urlopen(url)
  202. try:
  203. # Read all the data in one block.
  204. data = src.read()
  205. finally:
  206. src.close()
  207. # Write all the data in one block to avoid creating a partial file.
  208. with open(target, "wb") as dst:
  209. dst.write(data)
  210. download_file_insecure.viable = lambda: True
  211. def get_best_downloader():
  212. downloaders = (
  213. download_file_powershell,
  214. download_file_curl,
  215. download_file_wget,
  216. download_file_insecure,
  217. )
  218. viable_downloaders = (dl for dl in downloaders if dl.viable())
  219. return next(viable_downloaders, None)
  220. def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  221. to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
  222. """
  223. Download setuptools from a specified location and return its filename
  224. `version` should be a valid setuptools version number that is available
  225. as an sdist for download under the `download_base` URL (which should end
  226. with a '/'). `to_dir` is the directory where the egg will be downloaded.
  227. `delay` is the number of seconds to pause before an actual download
  228. attempt.
  229. ``downloader_factory`` should be a function taking no arguments and
  230. returning a function for downloading a URL to a target.
  231. """
  232. # making sure we use the absolute path
  233. to_dir = os.path.abspath(to_dir)
  234. zip_name = "setuptools-%s.zip" % version
  235. url = download_base + zip_name
  236. saveto = os.path.join(to_dir, zip_name)
  237. if not os.path.exists(saveto): # Avoid repeated downloads
  238. log.warn("Downloading %s", url)
  239. downloader = downloader_factory()
  240. downloader(url, saveto)
  241. return os.path.realpath(saveto)
  242. def _build_install_args(options):
  243. """
  244. Build the arguments to 'python setup.py install' on the setuptools package
  245. """
  246. return ['--user'] if options.user_install else []
  247. def _parse_args():
  248. """
  249. Parse the command line for options
  250. """
  251. parser = optparse.OptionParser()
  252. parser.add_option(
  253. '--user', dest='user_install', action='store_true', default=False,
  254. help='install in user site package (requires Python 2.6 or later)')
  255. parser.add_option(
  256. '--download-base', dest='download_base', metavar="URL",
  257. default=DEFAULT_URL,
  258. help='alternative URL from where to download the setuptools package')
  259. parser.add_option(
  260. '--insecure', dest='downloader_factory', action='store_const',
  261. const=lambda: download_file_insecure, default=get_best_downloader,
  262. help='Use internal, non-validating downloader'
  263. )
  264. parser.add_option(
  265. '--version', help="Specify which version to download",
  266. default=DEFAULT_VERSION,
  267. )
  268. options, args = parser.parse_args()
  269. # positional arguments are ignored
  270. return options
  271. def main():
  272. """Install or upgrade setuptools and EasyInstall"""
  273. options = _parse_args()
  274. archive = download_setuptools(
  275. version=options.version,
  276. download_base=options.download_base,
  277. downloader_factory=options.downloader_factory,
  278. )
  279. return _install(archive, _build_install_args(options))
  280. if __name__ == '__main__':
  281. sys.exit(main())