PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/ez_setup.py

https://gitlab.com/Rockyspade/astropy
Python | 382 lines | 350 code | 7 blank | 25 comment | 10 complexity | ab16e33b9160af2c02af534e697f6f29 MD5 | raw file
  1. #!python
  2. """Bootstrap setuptools installation
  3. If you want to use setuptools in your package's setup.py, just include this
  4. file in the same directory with it, and add this to the top of your setup.py::
  5. from ez_setup import use_setuptools
  6. use_setuptools()
  7. If you want to require a specific version of setuptools, set a download
  8. mirror, or use an alternate download directory, you can do so by supplying
  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 tarfile
  17. import optparse
  18. import subprocess
  19. import platform
  20. from distutils import log
  21. try:
  22. from site import USER_SITE
  23. except ImportError:
  24. USER_SITE = None
  25. DEFAULT_VERSION = "1.4.2"
  26. DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
  27. def _python_cmd(*args):
  28. args = (sys.executable,) + args
  29. return subprocess.call(args) == 0
  30. def _check_call_py24(cmd, *args, **kwargs):
  31. res = subprocess.call(cmd, *args, **kwargs)
  32. class CalledProcessError(Exception):
  33. pass
  34. if not res == 0:
  35. msg = "Command '%s' return non-zero exit status %d" % (cmd, res)
  36. raise CalledProcessError(msg)
  37. vars(subprocess).setdefault('check_call', _check_call_py24)
  38. def _install(tarball, install_args=()):
  39. # extracting the tarball
  40. tmpdir = tempfile.mkdtemp()
  41. log.warn('Extracting in %s', tmpdir)
  42. old_wd = os.getcwd()
  43. try:
  44. os.chdir(tmpdir)
  45. tar = tarfile.open(tarball)
  46. _extractall(tar)
  47. tar.close()
  48. # going in the directory
  49. subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
  50. os.chdir(subdir)
  51. log.warn('Now working in %s', subdir)
  52. # installing
  53. log.warn('Installing Setuptools')
  54. if not _python_cmd('setup.py', 'install', *install_args):
  55. log.warn('Something went wrong during the installation.')
  56. log.warn('See the error message above.')
  57. # exitcode will be 2
  58. return 2
  59. finally:
  60. os.chdir(old_wd)
  61. shutil.rmtree(tmpdir)
  62. def _build_egg(egg, tarball, to_dir):
  63. # extracting the tarball
  64. tmpdir = tempfile.mkdtemp()
  65. log.warn('Extracting in %s', tmpdir)
  66. old_wd = os.getcwd()
  67. try:
  68. os.chdir(tmpdir)
  69. tar = tarfile.open(tarball)
  70. _extractall(tar)
  71. tar.close()
  72. # going in the directory
  73. subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
  74. os.chdir(subdir)
  75. log.warn('Now working in %s', subdir)
  76. # building an egg
  77. log.warn('Building a Setuptools egg in %s', to_dir)
  78. _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
  79. finally:
  80. os.chdir(old_wd)
  81. shutil.rmtree(tmpdir)
  82. # returning the result
  83. log.warn(egg)
  84. if not os.path.exists(egg):
  85. raise IOError('Could not build the egg.')
  86. def _do_download(version, download_base, to_dir, download_delay):
  87. egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
  88. % (version, sys.version_info[0], sys.version_info[1]))
  89. if not os.path.exists(egg):
  90. tarball = download_setuptools(version, download_base,
  91. to_dir, download_delay)
  92. _build_egg(egg, tarball, to_dir)
  93. sys.path.insert(0, egg)
  94. # Remove previously-imported pkg_resources if present (see
  95. # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
  96. if 'pkg_resources' in sys.modules:
  97. del sys.modules['pkg_resources']
  98. import setuptools
  99. setuptools.bootstrap_install_from = egg
  100. def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  101. to_dir=os.curdir, download_delay=15):
  102. # making sure we use the absolute path
  103. to_dir = os.path.abspath(to_dir)
  104. was_imported = 'pkg_resources' in sys.modules or \
  105. 'setuptools' in sys.modules
  106. try:
  107. import pkg_resources
  108. except ImportError:
  109. return _do_download(version, download_base, to_dir, download_delay)
  110. try:
  111. pkg_resources.require("setuptools>=" + version)
  112. return
  113. except pkg_resources.VersionConflict:
  114. e = sys.exc_info()[1]
  115. if was_imported:
  116. sys.stderr.write(
  117. "The required version of setuptools (>=%s) is not available,\n"
  118. "and can't be installed while this script is running. Please\n"
  119. "install a more recent version first, using\n"
  120. "'easy_install -U setuptools'."
  121. "\n\n(Currently using %r)\n" % (version, e.args[0]))
  122. sys.exit(2)
  123. else:
  124. del pkg_resources, sys.modules['pkg_resources'] # reload ok
  125. return _do_download(version, download_base, to_dir,
  126. download_delay)
  127. except pkg_resources.DistributionNotFound:
  128. return _do_download(version, download_base, to_dir,
  129. download_delay)
  130. def _clean_check(cmd, target):
  131. """
  132. Run the command to download target. If the command fails, clean up before
  133. re-raising the error.
  134. """
  135. try:
  136. subprocess.check_call(cmd)
  137. except subprocess.CalledProcessError:
  138. if os.access(target, os.F_OK):
  139. os.unlink(target)
  140. raise
  141. def download_file_powershell(url, target):
  142. """
  143. Download the file at url to target using Powershell (which will validate
  144. trust). Raise an exception if the command cannot complete.
  145. """
  146. target = os.path.abspath(target)
  147. cmd = [
  148. 'powershell',
  149. '-Command',
  150. "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(),
  151. ]
  152. _clean_check(cmd, target)
  153. def has_powershell():
  154. if platform.system() != 'Windows':
  155. return False
  156. cmd = ['powershell', '-Command', 'echo test']
  157. devnull = open(os.path.devnull, 'wb')
  158. try:
  159. try:
  160. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  161. except:
  162. return False
  163. finally:
  164. devnull.close()
  165. return True
  166. download_file_powershell.viable = has_powershell
  167. def download_file_curl(url, target):
  168. cmd = ['curl', url, '--silent', '--output', target]
  169. _clean_check(cmd, target)
  170. def has_curl():
  171. cmd = ['curl', '--version']
  172. devnull = open(os.path.devnull, 'wb')
  173. try:
  174. try:
  175. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  176. except:
  177. return False
  178. finally:
  179. devnull.close()
  180. return True
  181. download_file_curl.viable = has_curl
  182. def download_file_wget(url, target):
  183. cmd = ['wget', url, '--quiet', '--output-document', target]
  184. _clean_check(cmd, target)
  185. def has_wget():
  186. cmd = ['wget', '--version']
  187. devnull = open(os.path.devnull, 'wb')
  188. try:
  189. try:
  190. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  191. except:
  192. return False
  193. finally:
  194. devnull.close()
  195. return True
  196. download_file_wget.viable = has_wget
  197. def download_file_insecure(url, target):
  198. """
  199. Use Python to download the file, even though it cannot authenticate the
  200. connection.
  201. """
  202. try:
  203. from urllib.request import urlopen
  204. except ImportError:
  205. from urllib2 import urlopen
  206. src = dst = None
  207. try:
  208. src = urlopen(url)
  209. # Read/write all in one block, so we don't create a corrupt file
  210. # if the download is interrupted.
  211. data = src.read()
  212. dst = open(target, "wb")
  213. dst.write(data)
  214. finally:
  215. if src:
  216. src.close()
  217. if dst:
  218. dst.close()
  219. download_file_insecure.viable = lambda: True
  220. def get_best_downloader():
  221. downloaders = [
  222. download_file_powershell,
  223. download_file_curl,
  224. download_file_wget,
  225. download_file_insecure,
  226. ]
  227. for dl in downloaders:
  228. if dl.viable():
  229. return dl
  230. def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  231. to_dir=os.curdir, delay=15,
  232. downloader_factory=get_best_downloader):
  233. """Download setuptools from a specified location and return its filename
  234. `version` should be a valid setuptools version number that is available
  235. as an egg for download under the `download_base` URL (which should end
  236. with a '/'). `to_dir` is the directory where the egg will be downloaded.
  237. `delay` is the number of seconds to pause before an actual download
  238. attempt.
  239. ``downloader_factory`` should be a function taking no arguments and
  240. returning a function for downloading a URL to a target.
  241. """
  242. # making sure we use the absolute path
  243. to_dir = os.path.abspath(to_dir)
  244. tgz_name = "setuptools-%s.tar.gz" % version
  245. url = download_base + tgz_name
  246. saveto = os.path.join(to_dir, tgz_name)
  247. if not os.path.exists(saveto): # Avoid repeated downloads
  248. log.warn("Downloading %s", url)
  249. downloader = downloader_factory()
  250. downloader(url, saveto)
  251. return os.path.realpath(saveto)
  252. def _extractall(self, path=".", members=None):
  253. """Extract all members from the archive to the current working
  254. directory and set owner, modification time and permissions on
  255. directories afterwards. `path' specifies a different directory
  256. to extract to. `members' is optional and must be a subset of the
  257. list returned by getmembers().
  258. """
  259. import copy
  260. import operator
  261. from tarfile import ExtractError
  262. directories = []
  263. if members is None:
  264. members = self
  265. for tarinfo in members:
  266. if tarinfo.isdir():
  267. # Extract directories with a safe mode.
  268. directories.append(tarinfo)
  269. tarinfo = copy.copy(tarinfo)
  270. tarinfo.mode = 448 # decimal for oct 0700
  271. self.extract(tarinfo, path)
  272. # Reverse sort directories.
  273. if sys.version_info < (2, 4):
  274. def sorter(dir1, dir2):
  275. return cmp(dir1.name, dir2.name)
  276. directories.sort(sorter)
  277. directories.reverse()
  278. else:
  279. directories.sort(key=operator.attrgetter('name'), reverse=True)
  280. # Set correct owner, mtime and filemode on directories.
  281. for tarinfo in directories:
  282. dirpath = os.path.join(path, tarinfo.name)
  283. try:
  284. self.chown(tarinfo, dirpath)
  285. self.utime(tarinfo, dirpath)
  286. self.chmod(tarinfo, dirpath)
  287. except ExtractError:
  288. e = sys.exc_info()[1]
  289. if self.errorlevel > 1:
  290. raise
  291. else:
  292. self._dbg(1, "tarfile: %s" % e)
  293. def _build_install_args(options):
  294. """
  295. Build the arguments to 'python setup.py install' on the setuptools package
  296. """
  297. install_args = []
  298. if options.user_install:
  299. if sys.version_info < (2, 6):
  300. log.warn("--user requires Python 2.6 or later")
  301. raise SystemExit(1)
  302. install_args.append('--user')
  303. return install_args
  304. def _parse_args():
  305. """
  306. Parse the command line for options
  307. """
  308. parser = optparse.OptionParser()
  309. parser.add_option(
  310. '--user', dest='user_install', action='store_true', default=False,
  311. help='install in user site package (requires Python 2.6 or later)')
  312. parser.add_option(
  313. '--download-base', dest='download_base', metavar="URL",
  314. default=DEFAULT_URL,
  315. help='alternative URL from where to download the setuptools package')
  316. parser.add_option(
  317. '--insecure', dest='downloader_factory', action='store_const',
  318. const=lambda: download_file_insecure, default=get_best_downloader,
  319. help='Use internal, non-validating downloader'
  320. )
  321. options, args = parser.parse_args()
  322. # positional arguments are ignored
  323. return options
  324. def main(version=DEFAULT_VERSION):
  325. """Install or upgrade setuptools and EasyInstall"""
  326. options = _parse_args()
  327. tarball = download_setuptools(download_base=options.download_base,
  328. downloader_factory=options.downloader_factory)
  329. return _install(tarball, _build_install_args(options))
  330. if __name__ == '__main__':
  331. sys.exit(main())