bootstrap.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2006 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Bootstrap a buildout-based project
  15. Simply run this script in a directory containing a buildout.cfg.
  16. The script accepts buildout command-line options, so you can
  17. use the -c option to specify an alternate configuration file.
  18. """
  19. import os, shutil, sys, tempfile, urllib, urllib2, subprocess
  20. from optparse import OptionParser
  21. if sys.platform == 'win32':
  22. def quote(c):
  23. if ' ' in c:
  24. return '"%s"' % c # work around spawn lamosity on windows
  25. else:
  26. return c
  27. else:
  28. quote = str
  29. # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
  30. stdout, stderr = subprocess.Popen(
  31. [sys.executable, '-Sc',
  32. 'try:\n'
  33. ' import ConfigParser\n'
  34. 'except ImportError:\n'
  35. ' print 1\n'
  36. 'else:\n'
  37. ' print 0\n'],
  38. stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  39. has_broken_dash_S = bool(int(stdout.strip()))
  40. # In order to be more robust in the face of system Pythons, we want to
  41. # run without site-packages loaded. This is somewhat tricky, in
  42. # particular because Python 2.6's distutils imports site, so starting
  43. # with the -S flag is not sufficient. However, we'll start with that:
  44. if not has_broken_dash_S and 'site' in sys.modules:
  45. # We will restart with python -S.
  46. args = sys.argv[:]
  47. args[0:0] = [sys.executable, '-S']
  48. args = map(quote, args)
  49. os.execv(sys.executable, args)
  50. # Now we are running with -S. We'll get the clean sys.path, import site
  51. # because distutils will do it later, and then reset the path and clean
  52. # out any namespace packages from site-packages that might have been
  53. # loaded by .pth files.
  54. clean_path = sys.path[:]
  55. import site # imported because of its side effects
  56. sys.path[:] = clean_path
  57. for k, v in sys.modules.items():
  58. if k in ('setuptools', 'pkg_resources') or (
  59. hasattr(v, '__path__') and
  60. len(v.__path__) == 1 and
  61. not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
  62. # This is a namespace package. Remove it.
  63. sys.modules.pop(k)
  64. is_jython = sys.platform.startswith('java')
  65. setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
  66. distribute_source = 'http://python-distribute.org/distribute_setup.py'
  67. distribute_source = 'https://bitbucket.org/pypa/setuptools/raw/f657df1f1ed46596d236376649c99a470662b4ba/distribute_setup.py'
  68. # parsing arguments
  69. def normalize_to_url(option, opt_str, value, parser):
  70. if value:
  71. if '://' not in value: # It doesn't smell like a URL.
  72. value = 'file://%s' % (
  73. urllib.pathname2url(
  74. os.path.abspath(os.path.expanduser(value))),)
  75. if opt_str == '--download-base' and not value.endswith('/'):
  76. # Download base needs a trailing slash to make the world happy.
  77. value += '/'
  78. else:
  79. value = None
  80. name = opt_str[2:].replace('-', '_')
  81. setattr(parser.values, name, value)
  82. usage = '''\
  83. [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
  84. Bootstraps a buildout-based project.
  85. Simply run this script in a directory containing a buildout.cfg, using the
  86. Python that you want bin/buildout to use.
  87. Note that by using --setup-source and --download-base to point to
  88. local resources, you can keep this script from going over the network.
  89. '''
  90. parser = OptionParser(usage=usage)
  91. parser.add_option("-v", "--version", dest="version",
  92. help="use a specific zc.buildout version")
  93. parser.add_option("-d", "--distribute",
  94. action="store_true", dest="use_distribute", default=False,
  95. help="Use Distribute rather than Setuptools.")
  96. parser.add_option("--setup-source", action="callback", dest="setup_source",
  97. callback=normalize_to_url, nargs=1, type="string",
  98. help=("Specify a URL or file location for the setup file. "
  99. "If you use Setuptools, this will default to " +
  100. setuptools_source + "; if you use Distribute, this "
  101. "will default to " + distribute_source + "."))
  102. parser.add_option("--download-base", action="callback", dest="download_base",
  103. callback=normalize_to_url, nargs=1, type="string",
  104. help=("Specify a URL or directory for downloading "
  105. "zc.buildout and either Setuptools or Distribute. "
  106. "Defaults to PyPI."))
  107. parser.add_option("--eggs",
  108. help=("Specify a directory for storing eggs. Defaults to "
  109. "a temporary directory that is deleted when the "
  110. "bootstrap script completes."))
  111. parser.add_option("-t", "--accept-buildout-test-releases",
  112. dest='accept_buildout_test_releases',
  113. action="store_true", default=False,
  114. help=("Normally, if you do not specify a --version, the "
  115. "bootstrap script and buildout gets the newest "
  116. "*final* versions of zc.buildout and its recipes and "
  117. "extensions for you. If you use this flag, "
  118. "bootstrap and buildout will get the newest releases "
  119. "even if they are alphas or betas."))
  120. parser.add_option("-c", None, action="store", dest="config_file",
  121. help=("Specify the path to the buildout configuration "
  122. "file to be used."))
  123. options, args = parser.parse_args()
  124. if options.eggs:
  125. eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
  126. else:
  127. eggs_dir = tempfile.mkdtemp()
  128. if options.setup_source is None:
  129. if options.use_distribute:
  130. options.setup_source = distribute_source
  131. else:
  132. options.setup_source = setuptools_source
  133. if options.accept_buildout_test_releases:
  134. args.insert(0, 'buildout:accept-buildout-test-releases=true')
  135. try:
  136. import pkg_resources
  137. import setuptools # A flag. Sometimes pkg_resources is installed alone.
  138. if not hasattr(pkg_resources, '_distribute'):
  139. raise ImportError
  140. except ImportError:
  141. ez_code = urllib2.urlopen(
  142. options.setup_source).read().replace('\r\n', '\n')
  143. ez = {}
  144. exec ez_code in ez
  145. setup_args = dict(to_dir=eggs_dir, download_delay=0)
  146. if options.download_base:
  147. setup_args['download_base'] = options.download_base
  148. if options.use_distribute:
  149. setup_args['no_fake'] = True
  150. if sys.version_info[:2] == (2, 4):
  151. setup_args['version'] = '0.6.32'
  152. ez['use_setuptools'](**setup_args)
  153. if 'pkg_resources' in sys.modules:
  154. reload(sys.modules['pkg_resources'])
  155. import pkg_resources
  156. # This does not (always?) update the default working set. We will
  157. # do it.
  158. for path in sys.path:
  159. if path not in pkg_resources.working_set.entries:
  160. pkg_resources.working_set.add_entry(path)
  161. cmd = [quote(sys.executable),
  162. '-c',
  163. quote('from setuptools.command.easy_install import main; main()'),
  164. '-mqNxd',
  165. quote(eggs_dir)]
  166. if not has_broken_dash_S:
  167. cmd.insert(1, '-S')
  168. find_links = options.download_base
  169. if not find_links:
  170. find_links = os.environ.get('bootstrap-testing-find-links')
  171. if not find_links and options.accept_buildout_test_releases:
  172. find_links = 'http://downloads.buildout.org/'
  173. if find_links:
  174. cmd.extend(['-f', quote(find_links)])
  175. if options.use_distribute:
  176. setup_requirement = 'distribute'
  177. else:
  178. setup_requirement = 'setuptools'
  179. ws = pkg_resources.working_set
  180. setup_requirement_path = ws.find(
  181. pkg_resources.Requirement.parse(setup_requirement)).location
  182. env = dict(
  183. os.environ,
  184. PYTHONPATH=setup_requirement_path)
  185. requirement = 'zc.buildout'
  186. version = options.version
  187. if version is None and not options.accept_buildout_test_releases:
  188. # Figure out the most recent final version of zc.buildout.
  189. import setuptools.package_index
  190. _final_parts = '*final-', '*final'
  191. def _final_version(parsed_version):
  192. for part in parsed_version:
  193. if (part[:1] == '*') and (part not in _final_parts):
  194. return False
  195. return True
  196. index = setuptools.package_index.PackageIndex(
  197. search_path=[setup_requirement_path])
  198. if find_links:
  199. index.add_find_links((find_links,))
  200. req = pkg_resources.Requirement.parse(requirement)
  201. if index.obtain(req) is not None:
  202. best = []
  203. bestv = None
  204. for dist in index[req.project_name]:
  205. distv = dist.parsed_version
  206. if distv >= pkg_resources.parse_version('2dev'):
  207. continue
  208. if _final_version(distv):
  209. if bestv is None or distv > bestv:
  210. best = [dist]
  211. bestv = distv
  212. elif distv == bestv:
  213. best.append(dist)
  214. if best:
  215. best.sort()
  216. version = best[-1].version
  217. if version:
  218. requirement += '=='+version
  219. else:
  220. requirement += '<2dev'
  221. cmd.append(requirement)
  222. if is_jython:
  223. import subprocess
  224. exitcode = subprocess.Popen(cmd, env=env).wait()
  225. else: # Windows prefers this, apparently; otherwise we would prefer subprocess
  226. exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
  227. if exitcode != 0:
  228. sys.stdout.flush()
  229. sys.stderr.flush()
  230. print ("An error occurred when trying to install zc.buildout. "
  231. "Look above this message for any errors that "
  232. "were output by easy_install.")
  233. sys.exit(exitcode)
  234. ws.add_entry(eggs_dir)
  235. ws.require(requirement)
  236. import zc.buildout.buildout
  237. # If there isn't already a command in the args, add bootstrap
  238. if not [a for a in args if '=' not in a]:
  239. args.append('bootstrap')
  240. # if -c was provided, we push it back into args for buildout's main function
  241. if options.config_file is not None:
  242. args[0:0] = ['-c', options.config_file]
  243. zc.buildout.buildout.main(args)
  244. if not options.eggs: # clean up temporary egg directory
  245. shutil.rmtree(eggs_dir)