PageRenderTime 35ms CodeModel.GetById 6ms RepoModel.GetById 1ms app.codeStats 0ms

/setuptools/command/easy_install.py

https://bitbucket.org/mumak/distribute
Python | 1939 lines | 1863 code | 38 blank | 38 comment | 80 complexity | 23618f58502017b472190214b6fe9598 MD5 | raw file
  1. #!python
  2. """\
  3. Easy Install
  4. ------------
  5. A tool for doing automatic download/extract/build of distutils-based Python
  6. packages. For detailed documentation, see the accompanying EasyInstall.txt
  7. file, or visit the `EasyInstall home page`__.
  8. __ http://packages.python.org/distribute/easy_install.html
  9. """
  10. import sys
  11. import os
  12. import zipimport
  13. import shutil
  14. import tempfile
  15. import zipfile
  16. import re
  17. import stat
  18. import random
  19. from glob import glob
  20. from setuptools import Command, _dont_write_bytecode
  21. from setuptools.sandbox import run_setup
  22. from distutils import log, dir_util
  23. from distutils.util import get_platform
  24. from distutils.util import convert_path, subst_vars
  25. from distutils.sysconfig import get_python_lib, get_config_vars
  26. from distutils.errors import DistutilsArgError, DistutilsOptionError, \
  27. DistutilsError, DistutilsPlatformError
  28. from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
  29. from setuptools.command import setopt
  30. from setuptools.archive_util import unpack_archive
  31. from setuptools.package_index import PackageIndex
  32. from setuptools.package_index import URL_SCHEME
  33. from setuptools.command import bdist_egg, egg_info
  34. from pkg_resources import yield_lines, normalize_path, resource_string, \
  35. ensure_directory, get_distribution, find_distributions, \
  36. Environment, Requirement, Distribution, \
  37. PathMetadata, EggMetadata, WorkingSet, \
  38. DistributionNotFound, VersionConflict, \
  39. DEVELOP_DIST
  40. sys_executable = os.path.normpath(sys.executable)
  41. __all__ = [
  42. 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
  43. 'main', 'get_exe_prefixes',
  44. ]
  45. import site
  46. HAS_USER_SITE = not sys.version < "2.6" and site.ENABLE_USER_SITE
  47. import struct
  48. def is_64bit():
  49. return struct.calcsize("P") == 8
  50. def samefile(p1,p2):
  51. if hasattr(os.path,'samefile') and (
  52. os.path.exists(p1) and os.path.exists(p2)
  53. ):
  54. return os.path.samefile(p1,p2)
  55. return (
  56. os.path.normpath(os.path.normcase(p1)) ==
  57. os.path.normpath(os.path.normcase(p2))
  58. )
  59. if sys.version_info <= (3,):
  60. def _to_ascii(s):
  61. return s
  62. def isascii(s):
  63. try:
  64. unicode(s, 'ascii')
  65. return True
  66. except UnicodeError:
  67. return False
  68. else:
  69. def _to_ascii(s):
  70. return s.encode('ascii')
  71. def isascii(s):
  72. try:
  73. s.encode('ascii')
  74. return True
  75. except UnicodeError:
  76. return False
  77. class easy_install(Command):
  78. """Manage a download/build/install process"""
  79. description = "Find/get/install Python packages"
  80. command_consumes_arguments = True
  81. user_options = [
  82. ('prefix=', None, "installation prefix"),
  83. ("zip-ok", "z", "install package as a zipfile"),
  84. ("multi-version", "m", "make apps have to require() a version"),
  85. ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
  86. ("install-dir=", "d", "install package to DIR"),
  87. ("script-dir=", "s", "install scripts to DIR"),
  88. ("exclude-scripts", "x", "Don't install scripts"),
  89. ("always-copy", "a", "Copy all needed packages to install dir"),
  90. ("index-url=", "i", "base URL of Python Package Index"),
  91. ("find-links=", "f", "additional URL(s) to search for packages"),
  92. ("delete-conflicting", "D", "no longer needed; don't use this"),
  93. ("ignore-conflicts-at-my-risk", None,
  94. "no longer needed; don't use this"),
  95. ("build-directory=", "b",
  96. "download/extract/build in DIR; keep the results"),
  97. ('optimize=', 'O',
  98. "also compile with optimization: -O1 for \"python -O\", "
  99. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  100. ('record=', None,
  101. "filename in which to record list of installed files"),
  102. ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
  103. ('site-dirs=','S',"list of directories where .pth files work"),
  104. ('editable', 'e', "Install specified packages in editable form"),
  105. ('no-deps', 'N', "don't install dependencies"),
  106. ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
  107. ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"),
  108. ('version', None, "print version information and exit"),
  109. ('no-find-links', None,
  110. "Don't load find-links defined in packages being installed")
  111. ]
  112. boolean_options = [
  113. 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
  114. 'delete-conflicting', 'ignore-conflicts-at-my-risk', 'editable',
  115. 'no-deps', 'local-snapshots-ok', 'version'
  116. ]
  117. if HAS_USER_SITE:
  118. user_options.append(('user', None,
  119. "install in user site-package '%s'" % site.USER_SITE))
  120. boolean_options.append('user')
  121. negative_opt = {'always-unzip': 'zip-ok'}
  122. create_index = PackageIndex
  123. def initialize_options(self):
  124. if HAS_USER_SITE:
  125. whereami = os.path.abspath(__file__)
  126. self.user = whereami.startswith(site.USER_SITE)
  127. else:
  128. self.user = 0
  129. self.zip_ok = self.local_snapshots_ok = None
  130. self.install_dir = self.script_dir = self.exclude_scripts = None
  131. self.index_url = None
  132. self.find_links = None
  133. self.build_directory = None
  134. self.args = None
  135. self.optimize = self.record = None
  136. self.upgrade = self.always_copy = self.multi_version = None
  137. self.editable = self.no_deps = self.allow_hosts = None
  138. self.root = self.prefix = self.no_report = None
  139. self.version = None
  140. self.install_purelib = None # for pure module distributions
  141. self.install_platlib = None # non-pure (dists w/ extensions)
  142. self.install_headers = None # for C/C++ headers
  143. self.install_lib = None # set to either purelib or platlib
  144. self.install_scripts = None
  145. self.install_data = None
  146. self.install_base = None
  147. self.install_platbase = None
  148. if HAS_USER_SITE:
  149. self.install_userbase = site.USER_BASE
  150. self.install_usersite = site.USER_SITE
  151. else:
  152. self.install_userbase = None
  153. self.install_usersite = None
  154. self.no_find_links = None
  155. # Options not specifiable via command line
  156. self.package_index = None
  157. self.pth_file = self.always_copy_from = None
  158. self.delete_conflicting = None
  159. self.ignore_conflicts_at_my_risk = None
  160. self.site_dirs = None
  161. self.installed_projects = {}
  162. self.sitepy_installed = False
  163. # Always read easy_install options, even if we are subclassed, or have
  164. # an independent instance created. This ensures that defaults will
  165. # always come from the standard configuration file(s)' "easy_install"
  166. # section, even if this is a "develop" or "install" command, or some
  167. # other embedding.
  168. self._dry_run = None
  169. self.verbose = self.distribution.verbose
  170. self.distribution._set_command_options(
  171. self, self.distribution.get_option_dict('easy_install')
  172. )
  173. def delete_blockers(self, blockers):
  174. for filename in blockers:
  175. if os.path.exists(filename) or os.path.islink(filename):
  176. log.info("Deleting %s", filename)
  177. if not self.dry_run:
  178. if os.path.isdir(filename) and not os.path.islink(filename):
  179. rmtree(filename)
  180. else:
  181. os.unlink(filename)
  182. def finalize_options(self):
  183. if self.version:
  184. print 'distribute %s' % get_distribution('distribute').version
  185. sys.exit()
  186. py_version = sys.version.split()[0]
  187. prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
  188. self.config_vars = {'dist_name': self.distribution.get_name(),
  189. 'dist_version': self.distribution.get_version(),
  190. 'dist_fullname': self.distribution.get_fullname(),
  191. 'py_version': py_version,
  192. 'py_version_short': py_version[0:3],
  193. 'py_version_nodot': py_version[0] + py_version[2],
  194. 'sys_prefix': prefix,
  195. 'prefix': prefix,
  196. 'sys_exec_prefix': exec_prefix,
  197. 'exec_prefix': exec_prefix,
  198. # Only python 3.2+ has abiflags
  199. 'abiflags': getattr(sys, 'abiflags', ''),
  200. }
  201. if HAS_USER_SITE:
  202. self.config_vars['userbase'] = self.install_userbase
  203. self.config_vars['usersite'] = self.install_usersite
  204. # fix the install_dir if "--user" was used
  205. #XXX: duplicate of the code in the setup command
  206. if self.user and HAS_USER_SITE:
  207. self.create_home_path()
  208. if self.install_userbase is None:
  209. raise DistutilsPlatformError(
  210. "User base directory is not specified")
  211. self.install_base = self.install_platbase = self.install_userbase
  212. if os.name == 'posix':
  213. self.select_scheme("unix_user")
  214. else:
  215. self.select_scheme(os.name + "_user")
  216. self.expand_basedirs()
  217. self.expand_dirs()
  218. self._expand('install_dir','script_dir','build_directory','site_dirs')
  219. # If a non-default installation directory was specified, default the
  220. # script directory to match it.
  221. if self.script_dir is None:
  222. self.script_dir = self.install_dir
  223. if self.no_find_links is None:
  224. self.no_find_links = False
  225. # Let install_dir get set by install_lib command, which in turn
  226. # gets its info from the install command, and takes into account
  227. # --prefix and --home and all that other crud.
  228. self.set_undefined_options('install_lib',
  229. ('install_dir','install_dir')
  230. )
  231. # Likewise, set default script_dir from 'install_scripts.install_dir'
  232. self.set_undefined_options('install_scripts',
  233. ('install_dir', 'script_dir')
  234. )
  235. if self.user and self.install_purelib:
  236. self.install_dir = self.install_purelib
  237. self.script_dir = self.install_scripts
  238. # default --record from the install command
  239. self.set_undefined_options('install', ('record', 'record'))
  240. normpath = map(normalize_path, sys.path)
  241. self.all_site_dirs = get_site_dirs()
  242. if self.site_dirs is not None:
  243. site_dirs = [
  244. os.path.expanduser(s.strip()) for s in self.site_dirs.split(',')
  245. ]
  246. for d in site_dirs:
  247. if not os.path.isdir(d):
  248. log.warn("%s (in --site-dirs) does not exist", d)
  249. elif normalize_path(d) not in normpath:
  250. raise DistutilsOptionError(
  251. d+" (in --site-dirs) is not on sys.path"
  252. )
  253. else:
  254. self.all_site_dirs.append(normalize_path(d))
  255. if not self.editable: self.check_site_dir()
  256. self.index_url = self.index_url or "http://pypi.python.org/simple"
  257. self.shadow_path = self.all_site_dirs[:]
  258. for path_item in self.install_dir, normalize_path(self.script_dir):
  259. if path_item not in self.shadow_path:
  260. self.shadow_path.insert(0, path_item)
  261. if self.allow_hosts is not None:
  262. hosts = [s.strip() for s in self.allow_hosts.split(',')]
  263. else:
  264. hosts = ['*']
  265. if self.package_index is None:
  266. self.package_index = self.create_index(
  267. self.index_url, search_path = self.shadow_path, hosts=hosts,
  268. )
  269. self.local_index = Environment(self.shadow_path+sys.path)
  270. if self.find_links is not None:
  271. if isinstance(self.find_links, basestring):
  272. self.find_links = self.find_links.split()
  273. else:
  274. self.find_links = []
  275. if self.local_snapshots_ok:
  276. self.package_index.scan_egg_links(self.shadow_path+sys.path)
  277. if not self.no_find_links:
  278. self.package_index.add_find_links(self.find_links)
  279. self.set_undefined_options('install_lib', ('optimize','optimize'))
  280. if not isinstance(self.optimize,int):
  281. try:
  282. self.optimize = int(self.optimize)
  283. if not (0 <= self.optimize <= 2): raise ValueError
  284. except ValueError:
  285. raise DistutilsOptionError("--optimize must be 0, 1, or 2")
  286. if self.delete_conflicting and self.ignore_conflicts_at_my_risk:
  287. raise DistutilsOptionError(
  288. "Can't use both --delete-conflicting and "
  289. "--ignore-conflicts-at-my-risk at the same time"
  290. )
  291. if self.editable and not self.build_directory:
  292. raise DistutilsArgError(
  293. "Must specify a build directory (-b) when using --editable"
  294. )
  295. if not self.args:
  296. raise DistutilsArgError(
  297. "No urls, filenames, or requirements specified (see --help)")
  298. self.outputs = []
  299. def _expand_attrs(self, attrs):
  300. for attr in attrs:
  301. val = getattr(self, attr)
  302. if val is not None:
  303. if os.name == 'posix' or os.name == 'nt':
  304. val = os.path.expanduser(val)
  305. val = subst_vars(val, self.config_vars)
  306. setattr(self, attr, val)
  307. def expand_basedirs(self):
  308. """Calls `os.path.expanduser` on install_base, install_platbase and
  309. root."""
  310. self._expand_attrs(['install_base', 'install_platbase', 'root'])
  311. def expand_dirs(self):
  312. """Calls `os.path.expanduser` on install dirs."""
  313. self._expand_attrs(['install_purelib', 'install_platlib',
  314. 'install_lib', 'install_headers',
  315. 'install_scripts', 'install_data',])
  316. def run(self):
  317. if self.verbose != self.distribution.verbose:
  318. log.set_verbosity(self.verbose)
  319. try:
  320. for spec in self.args:
  321. self.easy_install(spec, not self.no_deps)
  322. if self.record:
  323. outputs = self.outputs
  324. if self.root: # strip any package prefix
  325. root_len = len(self.root)
  326. for counter in xrange(len(outputs)):
  327. outputs[counter] = outputs[counter][root_len:]
  328. from distutils import file_util
  329. self.execute(
  330. file_util.write_file, (self.record, outputs),
  331. "writing list of installed files to '%s'" %
  332. self.record
  333. )
  334. self.warn_deprecated_options()
  335. finally:
  336. log.set_verbosity(self.distribution.verbose)
  337. def pseudo_tempname(self):
  338. """Return a pseudo-tempname base in the install directory.
  339. This code is intentionally naive; if a malicious party can write to
  340. the target directory you're already in deep doodoo.
  341. """
  342. try:
  343. pid = os.getpid()
  344. except:
  345. pid = random.randint(0,sys.maxint)
  346. return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
  347. def warn_deprecated_options(self):
  348. if self.delete_conflicting or self.ignore_conflicts_at_my_risk:
  349. log.warn(
  350. "Note: The -D, --delete-conflicting and"
  351. " --ignore-conflicts-at-my-risk no longer have any purpose"
  352. " and should not be used."
  353. )
  354. def check_site_dir(self):
  355. """Verify that self.install_dir is .pth-capable dir, if needed"""
  356. instdir = normalize_path(self.install_dir)
  357. pth_file = os.path.join(instdir,'easy-install.pth')
  358. # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
  359. is_site_dir = instdir in self.all_site_dirs
  360. if not is_site_dir:
  361. # No? Then directly test whether it does .pth file processing
  362. is_site_dir = self.check_pth_processing()
  363. else:
  364. # make sure we can write to target dir
  365. testfile = self.pseudo_tempname()+'.write-test'
  366. test_exists = os.path.exists(testfile)
  367. try:
  368. if test_exists: os.unlink(testfile)
  369. open(testfile,'w').close()
  370. os.unlink(testfile)
  371. except (OSError,IOError):
  372. self.cant_write_to_target()
  373. if not is_site_dir and not self.multi_version:
  374. # Can't install non-multi to non-site dir
  375. raise DistutilsError(self.no_default_version_msg())
  376. if is_site_dir:
  377. if self.pth_file is None:
  378. self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
  379. else:
  380. self.pth_file = None
  381. PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep)
  382. if instdir not in map(normalize_path, filter(None,PYTHONPATH)):
  383. # only PYTHONPATH dirs need a site.py, so pretend it's there
  384. self.sitepy_installed = True
  385. elif self.multi_version and not os.path.exists(pth_file):
  386. self.sitepy_installed = True # don't need site.py in this case
  387. self.pth_file = None # and don't create a .pth file
  388. self.install_dir = instdir
  389. def cant_write_to_target(self):
  390. msg = """can't create or remove files in install directory
  391. The following error occurred while trying to add or remove files in the
  392. installation directory:
  393. %s
  394. The installation directory you specified (via --install-dir, --prefix, or
  395. the distutils default setting) was:
  396. %s
  397. """ % (sys.exc_info()[1], self.install_dir,)
  398. if not os.path.exists(self.install_dir):
  399. msg += """
  400. This directory does not currently exist. Please create it and try again, or
  401. choose a different installation directory (using the -d or --install-dir
  402. option).
  403. """
  404. else:
  405. msg += """
  406. Perhaps your account does not have write access to this directory? If the
  407. installation directory is a system-owned directory, you may need to sign in
  408. as the administrator or "root" account. If you do not have administrative
  409. access to this machine, you may wish to choose a different installation
  410. directory, preferably one that is listed in your PYTHONPATH environment
  411. variable.
  412. For information on other options, you may wish to consult the
  413. documentation at:
  414. http://packages.python.org/distribute/easy_install.html
  415. Please make the appropriate changes for your system and try again.
  416. """
  417. raise DistutilsError(msg)
  418. def check_pth_processing(self):
  419. """Empirically verify whether .pth files are supported in inst. dir"""
  420. instdir = self.install_dir
  421. log.info("Checking .pth file support in %s", instdir)
  422. pth_file = self.pseudo_tempname()+".pth"
  423. ok_file = pth_file+'.ok'
  424. ok_exists = os.path.exists(ok_file)
  425. try:
  426. if ok_exists: os.unlink(ok_file)
  427. dirname = os.path.dirname(ok_file)
  428. if not os.path.exists(dirname):
  429. os.makedirs(dirname)
  430. f = open(pth_file,'w')
  431. except (OSError,IOError):
  432. self.cant_write_to_target()
  433. else:
  434. try:
  435. f.write("import os;open(%r,'w').write('OK')\n" % (ok_file,))
  436. f.close(); f=None
  437. executable = sys.executable
  438. if os.name=='nt':
  439. dirname,basename = os.path.split(executable)
  440. alt = os.path.join(dirname,'pythonw.exe')
  441. if basename.lower()=='python.exe' and os.path.exists(alt):
  442. # use pythonw.exe to avoid opening a console window
  443. executable = alt
  444. from distutils.spawn import spawn
  445. spawn([executable,'-E','-c','pass'],0)
  446. if os.path.exists(ok_file):
  447. log.info(
  448. "TEST PASSED: %s appears to support .pth files",
  449. instdir
  450. )
  451. return True
  452. finally:
  453. if f: f.close()
  454. if os.path.exists(ok_file): os.unlink(ok_file)
  455. if os.path.exists(pth_file): os.unlink(pth_file)
  456. if not self.multi_version:
  457. log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
  458. return False
  459. def install_egg_scripts(self, dist):
  460. """Write all the scripts for `dist`, unless scripts are excluded"""
  461. if not self.exclude_scripts and dist.metadata_isdir('scripts'):
  462. for script_name in dist.metadata_listdir('scripts'):
  463. self.install_script(
  464. dist, script_name,
  465. dist.get_metadata('scripts/'+script_name)
  466. )
  467. self.install_wrapper_scripts(dist)
  468. def add_output(self, path):
  469. if os.path.isdir(path):
  470. for base, dirs, files in os.walk(path):
  471. for filename in files:
  472. self.outputs.append(os.path.join(base,filename))
  473. else:
  474. self.outputs.append(path)
  475. def not_editable(self, spec):
  476. if self.editable:
  477. raise DistutilsArgError(
  478. "Invalid argument %r: you can't use filenames or URLs "
  479. "with --editable (except via the --find-links option)."
  480. % (spec,)
  481. )
  482. def check_editable(self,spec):
  483. if not self.editable:
  484. return
  485. if os.path.exists(os.path.join(self.build_directory, spec.key)):
  486. raise DistutilsArgError(
  487. "%r already exists in %s; can't do a checkout there" %
  488. (spec.key, self.build_directory)
  489. )
  490. def easy_install(self, spec, deps=False):
  491. tmpdir = tempfile.mkdtemp(prefix="easy_install-")
  492. download = None
  493. if not self.editable: self.install_site_py()
  494. try:
  495. if not isinstance(spec,Requirement):
  496. if URL_SCHEME(spec):
  497. # It's a url, download it to tmpdir and process
  498. self.not_editable(spec)
  499. download = self.package_index.download(spec, tmpdir)
  500. return self.install_item(None, download, tmpdir, deps, True)
  501. elif os.path.exists(spec):
  502. # Existing file or directory, just process it directly
  503. self.not_editable(spec)
  504. return self.install_item(None, spec, tmpdir, deps, True)
  505. else:
  506. spec = parse_requirement_arg(spec)
  507. self.check_editable(spec)
  508. dist = self.package_index.fetch_distribution(
  509. spec, tmpdir, self.upgrade, self.editable, not self.always_copy,
  510. self.local_index
  511. )
  512. if dist is None:
  513. msg = "Could not find suitable distribution for %r" % spec
  514. if self.always_copy:
  515. msg+=" (--always-copy skips system and development eggs)"
  516. raise DistutilsError(msg)
  517. elif dist.precedence==DEVELOP_DIST:
  518. # .egg-info dists don't need installing, just process deps
  519. self.process_distribution(spec, dist, deps, "Using")
  520. return dist
  521. else:
  522. return self.install_item(spec, dist.location, tmpdir, deps)
  523. finally:
  524. if os.path.exists(tmpdir):
  525. rmtree(tmpdir)
  526. def install_item(self, spec, download, tmpdir, deps, install_needed=False):
  527. # Installation is also needed if file in tmpdir or is not an egg
  528. install_needed = install_needed or self.always_copy
  529. install_needed = install_needed or os.path.dirname(download) == tmpdir
  530. install_needed = install_needed or not download.endswith('.egg')
  531. install_needed = install_needed or (
  532. self.always_copy_from is not None and
  533. os.path.dirname(normalize_path(download)) ==
  534. normalize_path(self.always_copy_from)
  535. )
  536. if spec and not install_needed:
  537. # at this point, we know it's a local .egg, we just don't know if
  538. # it's already installed.
  539. for dist in self.local_index[spec.project_name]:
  540. if dist.location==download:
  541. break
  542. else:
  543. install_needed = True # it's not in the local index
  544. log.info("Processing %s", os.path.basename(download))
  545. if install_needed:
  546. dists = self.install_eggs(spec, download, tmpdir)
  547. for dist in dists:
  548. self.process_distribution(spec, dist, deps)
  549. else:
  550. dists = [self.check_conflicts(self.egg_distribution(download))]
  551. self.process_distribution(spec, dists[0], deps, "Using")
  552. if spec is not None:
  553. for dist in dists:
  554. if dist in spec:
  555. return dist
  556. def select_scheme(self, name):
  557. """Sets the install directories by applying the install schemes."""
  558. # it's the caller's problem if they supply a bad name!
  559. scheme = INSTALL_SCHEMES[name]
  560. for key in SCHEME_KEYS:
  561. attrname = 'install_' + key
  562. if getattr(self, attrname) is None:
  563. setattr(self, attrname, scheme[key])
  564. def process_distribution(self, requirement, dist, deps=True, *info):
  565. self.update_pth(dist)
  566. self.package_index.add(dist)
  567. self.local_index.add(dist)
  568. if not self.editable:
  569. self.install_egg_scripts(dist)
  570. self.installed_projects[dist.key] = dist
  571. log.info(self.installation_report(requirement, dist, *info))
  572. if (dist.has_metadata('dependency_links.txt') and
  573. not self.no_find_links):
  574. self.package_index.add_find_links(
  575. dist.get_metadata_lines('dependency_links.txt')
  576. )
  577. if not deps and not self.always_copy:
  578. return
  579. elif requirement is not None and dist.key != requirement.key:
  580. log.warn("Skipping dependencies for %s", dist)
  581. return # XXX this is not the distribution we were looking for
  582. elif requirement is None or dist not in requirement:
  583. # if we wound up with a different version, resolve what we've got
  584. distreq = dist.as_requirement()
  585. requirement = requirement or distreq
  586. requirement = Requirement(
  587. distreq.project_name, distreq.specs, requirement.extras
  588. )
  589. log.info("Processing dependencies for %s", requirement)
  590. try:
  591. distros = WorkingSet([]).resolve(
  592. [requirement], self.local_index, self.easy_install
  593. )
  594. except DistributionNotFound, e:
  595. raise DistutilsError(
  596. "Could not find required distribution %s" % e.args
  597. )
  598. except VersionConflict, e:
  599. raise DistutilsError(
  600. "Installed distribution %s conflicts with requirement %s"
  601. % e.args
  602. )
  603. if self.always_copy or self.always_copy_from:
  604. # Force all the relevant distros to be copied or activated
  605. for dist in distros:
  606. if dist.key not in self.installed_projects:
  607. self.easy_install(dist.as_requirement())
  608. log.info("Finished processing dependencies for %s", requirement)
  609. def should_unzip(self, dist):
  610. if self.zip_ok is not None:
  611. return not self.zip_ok
  612. if dist.has_metadata('not-zip-safe'):
  613. return True
  614. if not dist.has_metadata('zip-safe'):
  615. return True
  616. return True
  617. def maybe_move(self, spec, dist_filename, setup_base):
  618. dst = os.path.join(self.build_directory, spec.key)
  619. if os.path.exists(dst):
  620. log.warn(
  621. "%r already exists in %s; build directory %s will not be kept",
  622. spec.key, self.build_directory, setup_base
  623. )
  624. return setup_base
  625. if os.path.isdir(dist_filename):
  626. setup_base = dist_filename
  627. else:
  628. if os.path.dirname(dist_filename)==setup_base:
  629. os.unlink(dist_filename) # get it out of the tmp dir
  630. contents = os.listdir(setup_base)
  631. if len(contents)==1:
  632. dist_filename = os.path.join(setup_base,contents[0])
  633. if os.path.isdir(dist_filename):
  634. # if the only thing there is a directory, move it instead
  635. setup_base = dist_filename
  636. ensure_directory(dst); shutil.move(setup_base, dst)
  637. return dst
  638. def install_wrapper_scripts(self, dist):
  639. if not self.exclude_scripts:
  640. for args in get_script_args(dist):
  641. self.write_script(*args)
  642. def install_script(self, dist, script_name, script_text, dev_path=None):
  643. """Generate a legacy script wrapper and install it"""
  644. spec = str(dist.as_requirement())
  645. is_script = is_python_script(script_text, script_name)
  646. def get_template(filename):
  647. """
  648. There are a couple of template scripts in the package. This
  649. function loads one of them and prepares it for use.
  650. These templates use triple-quotes to escape variable
  651. substitutions so the scripts get the 2to3 treatment when build
  652. on Python 3. The templates cannot use triple-quotes naturally.
  653. """
  654. raw_bytes = resource_string('setuptools', template_name)
  655. template_str = raw_bytes.decode('utf-8')
  656. clean_template = template_str.replace('"""', '')
  657. return clean_template
  658. if is_script:
  659. template_name = 'script template.py'
  660. if dev_path:
  661. template_name = template_name.replace('.py', ' (dev).py')
  662. script_text = (get_script_header(script_text) +
  663. get_template(template_name) % locals())
  664. self.write_script(script_name, _to_ascii(script_text), 'b')
  665. def write_script(self, script_name, contents, mode="t", blockers=()):
  666. """Write an executable file to the scripts directory"""
  667. self.delete_blockers( # clean up old .py/.pyw w/o a script
  668. [os.path.join(self.script_dir,x) for x in blockers])
  669. log.info("Installing %s script to %s", script_name, self.script_dir)
  670. target = os.path.join(self.script_dir, script_name)
  671. self.add_output(target)
  672. mask = current_umask()
  673. if not self.dry_run:
  674. ensure_directory(target)
  675. f = open(target,"w"+mode)
  676. f.write(contents)
  677. f.close()
  678. chmod(target, 0777-mask)
  679. def install_eggs(self, spec, dist_filename, tmpdir):
  680. # .egg dirs or files are already built, so just return them
  681. if dist_filename.lower().endswith('.egg'):
  682. return [self.install_egg(dist_filename, tmpdir)]
  683. elif dist_filename.lower().endswith('.exe'):
  684. return [self.install_exe(dist_filename, tmpdir)]
  685. # Anything else, try to extract and build
  686. setup_base = tmpdir
  687. if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
  688. unpack_archive(dist_filename, tmpdir, self.unpack_progress)
  689. elif os.path.isdir(dist_filename):
  690. setup_base = os.path.abspath(dist_filename)
  691. if (setup_base.startswith(tmpdir) # something we downloaded
  692. and self.build_directory and spec is not None
  693. ):
  694. setup_base = self.maybe_move(spec, dist_filename, setup_base)
  695. # Find the setup.py file
  696. setup_script = os.path.join(setup_base, 'setup.py')
  697. if not os.path.exists(setup_script):
  698. setups = glob(os.path.join(setup_base, '*', 'setup.py'))
  699. if not setups:
  700. raise DistutilsError(
  701. "Couldn't find a setup script in %s" % os.path.abspath(dist_filename)
  702. )
  703. if len(setups)>1:
  704. raise DistutilsError(
  705. "Multiple setup scripts in %s" % os.path.abspath(dist_filename)
  706. )
  707. setup_script = setups[0]
  708. # Now run it, and return the result
  709. if self.editable:
  710. log.info(self.report_editable(spec, setup_script))
  711. return []
  712. else:
  713. return self.build_and_install(setup_script, setup_base)
  714. def egg_distribution(self, egg_path):
  715. if os.path.isdir(egg_path):
  716. metadata = PathMetadata(egg_path,os.path.join(egg_path,'EGG-INFO'))
  717. else:
  718. metadata = EggMetadata(zipimport.zipimporter(egg_path))
  719. return Distribution.from_filename(egg_path,metadata=metadata)
  720. def install_egg(self, egg_path, tmpdir):
  721. destination = os.path.join(self.install_dir,os.path.basename(egg_path))
  722. destination = os.path.abspath(destination)
  723. if not self.dry_run:
  724. ensure_directory(destination)
  725. dist = self.egg_distribution(egg_path)
  726. self.check_conflicts(dist)
  727. if not samefile(egg_path, destination):
  728. if os.path.isdir(destination) and not os.path.islink(destination):
  729. dir_util.remove_tree(destination, dry_run=self.dry_run)
  730. elif os.path.exists(destination):
  731. self.execute(os.unlink,(destination,),"Removing "+destination)
  732. uncache_zipdir(destination)
  733. if os.path.isdir(egg_path):
  734. if egg_path.startswith(tmpdir):
  735. f,m = shutil.move, "Moving"
  736. else:
  737. f,m = shutil.copytree, "Copying"
  738. elif self.should_unzip(dist):
  739. self.mkpath(destination)
  740. f,m = self.unpack_and_compile, "Extracting"
  741. elif egg_path.startswith(tmpdir):
  742. f,m = shutil.move, "Moving"
  743. else:
  744. f,m = shutil.copy2, "Copying"
  745. self.execute(f, (egg_path, destination),
  746. (m+" %s to %s") %
  747. (os.path.basename(egg_path),os.path.dirname(destination)))
  748. self.add_output(destination)
  749. return self.egg_distribution(destination)
  750. def install_exe(self, dist_filename, tmpdir):
  751. # See if it's valid, get data
  752. cfg = extract_wininst_cfg(dist_filename)
  753. if cfg is None:
  754. raise DistutilsError(
  755. "%s is not a valid distutils Windows .exe" % dist_filename
  756. )
  757. # Create a dummy distribution object until we build the real distro
  758. dist = Distribution(None,
  759. project_name=cfg.get('metadata','name'),
  760. version=cfg.get('metadata','version'), platform=get_platform()
  761. )
  762. # Convert the .exe to an unpacked egg
  763. egg_path = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg')
  764. egg_tmp = egg_path+'.tmp'
  765. egg_info = os.path.join(egg_tmp, 'EGG-INFO')
  766. pkg_inf = os.path.join(egg_info, 'PKG-INFO')
  767. ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
  768. dist._provider = PathMetadata(egg_tmp, egg_info) # XXX
  769. self.exe_to_egg(dist_filename, egg_tmp)
  770. # Write EGG-INFO/PKG-INFO
  771. if not os.path.exists(pkg_inf):
  772. f = open(pkg_inf,'w')
  773. f.write('Metadata-Version: 1.0\n')
  774. for k,v in cfg.items('metadata'):
  775. if k<>'target_version':
  776. f.write('%s: %s\n' % (k.replace('_','-').title(), v))
  777. f.close()
  778. script_dir = os.path.join(egg_info,'scripts')
  779. self.delete_blockers( # delete entry-point scripts to avoid duping
  780. [os.path.join(script_dir,args[0]) for args in get_script_args(dist)]
  781. )
  782. # Build .egg file from tmpdir
  783. bdist_egg.make_zipfile(
  784. egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run
  785. )
  786. # install the .egg
  787. return self.install_egg(egg_path, tmpdir)
  788. def exe_to_egg(self, dist_filename, egg_tmp):
  789. """Extract a bdist_wininst to the directories an egg would use"""
  790. # Check for .pth file and set up prefix translations
  791. prefixes = get_exe_prefixes(dist_filename)
  792. to_compile = []
  793. native_libs = []
  794. top_level = {}
  795. def process(src,dst):
  796. s = src.lower()
  797. for old,new in prefixes:
  798. if s.startswith(old):
  799. src = new+src[len(old):]
  800. parts = src.split('/')
  801. dst = os.path.join(egg_tmp, *parts)
  802. dl = dst.lower()
  803. if dl.endswith('.pyd') or dl.endswith('.dll'):
  804. parts[-1] = bdist_egg.strip_module(parts[-1])
  805. top_level[os.path.splitext(parts[0])[0]] = 1
  806. native_libs.append(src)
  807. elif dl.endswith('.py') and old!='SCRIPTS/':
  808. top_level[os.path.splitext(parts[0])[0]] = 1
  809. to_compile.append(dst)
  810. return dst
  811. if not src.endswith('.pth'):
  812. log.warn("WARNING: can't process %s", src)
  813. return None
  814. # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
  815. unpack_archive(dist_filename, egg_tmp, process)
  816. stubs = []
  817. for res in native_libs:
  818. if res.lower().endswith('.pyd'): # create stubs for .pyd's
  819. parts = res.split('/')
  820. resource = parts[-1]
  821. parts[-1] = bdist_egg.strip_module(parts[-1])+'.py'
  822. pyfile = os.path.join(egg_tmp, *parts)
  823. to_compile.append(pyfile); stubs.append(pyfile)
  824. bdist_egg.write_stub(resource, pyfile)
  825. self.byte_compile(to_compile) # compile .py's
  826. bdist_egg.write_safety_flag(os.path.join(egg_tmp,'EGG-INFO'),
  827. bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
  828. for name in 'top_level','native_libs':
  829. if locals()[name]:
  830. txt = os.path.join(egg_tmp, 'EGG-INFO', name+'.txt')
  831. if not os.path.exists(txt):
  832. f = open(txt,'w')
  833. f.write('\n'.join(locals()[name])+'\n')
  834. f.close()
  835. def check_conflicts(self, dist):
  836. """Verify that there are no conflicting "old-style" packages"""
  837. return dist # XXX temporarily disable until new strategy is stable
  838. from imp import find_module, get_suffixes
  839. from glob import glob
  840. blockers = []
  841. names = dict.fromkeys(dist._get_metadata('top_level.txt')) # XXX private attr
  842. exts = {'.pyc':1, '.pyo':1} # get_suffixes() might leave one out
  843. for ext,mode,typ in get_suffixes():
  844. exts[ext] = 1
  845. for path,files in expand_paths([self.install_dir]+self.all_site_dirs):
  846. for filename in files:
  847. base,ext = os.path.splitext(filename)
  848. if base in names:
  849. if not ext:
  850. # no extension, check for package
  851. try:
  852. f, filename, descr = find_module(base, [path])
  853. except ImportError:
  854. continue
  855. else:
  856. if f: f.close()
  857. if filename not in blockers:
  858. blockers.append(filename)
  859. elif ext in exts and base!='site': # XXX ugh
  860. blockers.append(os.path.join(path,filename))
  861. if blockers:
  862. self.found_conflicts(dist, blockers)
  863. return dist
  864. def found_conflicts(self, dist, blockers):
  865. if self.delete_conflicting:
  866. log.warn("Attempting to delete conflicting packages:")
  867. return self.delete_blockers(blockers)
  868. msg = """\
  869. -------------------------------------------------------------------------
  870. CONFLICT WARNING:
  871. The following modules or packages have the same names as modules or
  872. packages being installed, and will be *before* the installed packages in
  873. Python's search path. You MUST remove all of the relevant files and
  874. directories before you will be able to use the package(s) you are
  875. installing:
  876. %s
  877. """ % '\n '.join(blockers)
  878. if self.ignore_conflicts_at_my_risk:
  879. msg += """\
  880. (Note: you can run EasyInstall on '%s' with the
  881. --delete-conflicting option to attempt deletion of the above files
  882. and/or directories.)
  883. """ % dist.project_name
  884. else:
  885. msg += """\
  886. Note: you can attempt this installation again with EasyInstall, and use
  887. either the --delete-conflicting (-D) option or the
  888. --ignore-conflicts-at-my-risk option, to either delete the above files
  889. and directories, or to ignore the conflicts, respectively. Note that if
  890. you ignore the conflicts, the installed package(s) may not work.
  891. """
  892. msg += """\
  893. -------------------------------------------------------------------------
  894. """
  895. sys.stderr.write(msg)
  896. sys.stderr.flush()
  897. if not self.ignore_conflicts_at_my_risk:
  898. raise DistutilsError("Installation aborted due to conflicts")
  899. def installation_report(self, req, dist, what="Installed"):
  900. """Helpful installation message for display to package users"""
  901. msg = "\n%(what)s %(eggloc)s%(extras)s"
  902. if self.multi_version and not self.no_report:
  903. msg += """
  904. Because this distribution was installed --multi-version, before you can
  905. import modules from this package in an application, you will need to
  906. 'import pkg_resources' and then use a 'require()' call similar to one of
  907. these examples, in order to select the desired version:
  908. pkg_resources.require("%(name)s") # latest installed version
  909. pkg_resources.require("%(name)s==%(version)s") # this exact version
  910. pkg_resources.require("%(name)s>=%(version)s") # this version or higher
  911. """
  912. if self.install_dir not in map(normalize_path,sys.path):
  913. msg += """
  914. Note also that the installation directory must be on sys.path at runtime for
  915. this to work. (e.g. by being the application's script directory, by being on
  916. PYTHONPATH, or by being added to sys.path by your code.)
  917. """
  918. eggloc = dist.location
  919. name = dist.project_name
  920. version = dist.version
  921. extras = '' # TODO: self.report_extras(req, dist)
  922. return msg % locals()
  923. def report_editable(self, spec, setup_script):
  924. dirname = os.path.dirname(setup_script)
  925. python = sys.executable
  926. return """\nExtracted editable version of %(spec)s to %(dirname)s
  927. If it uses setuptools in its setup script, you can activate it in
  928. "development" mode by going to that directory and running::
  929. %(python)s setup.py develop
  930. See the setuptools documentation for the "develop" command for more info.
  931. """ % locals()
  932. def run_setup(self, setup_script, setup_base, args):
  933. sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
  934. sys.modules.setdefault('distutils.command.egg_info', egg_info)
  935. args = list(args)
  936. if self.verbose>2:
  937. v = 'v' * (self.verbose - 1)
  938. args.insert(0,'-'+v)
  939. elif self.verbose<2:
  940. args.insert(0,'-q')
  941. if self.dry_run:
  942. args.insert(0,'-n')
  943. log.info(
  944. "Running %s %s", setup_script[len(setup_base)+1:], ' '.join(args)
  945. )
  946. try:
  947. run_setup(setup_script, args)
  948. except SystemExit, v:
  949. raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  950. def build_and_install(self, setup_script, setup_base):
  951. args = ['bdist_egg', '--dist-dir']
  952. dist_dir = tempfile.mkdtemp(
  953. prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
  954. )
  955. try:
  956. self._set_fetcher_options(os.path.dirname(setup_script))
  957. args.append(dist_dir)
  958. self.run_setup(setup_script, setup_base, args)
  959. all_eggs = Environment([dist_dir])
  960. eggs = []
  961. for key in all_eggs:
  962. for dist in all_eggs[key]:
  963. eggs.append(self.install_egg(dist.location, setup_base))
  964. if not eggs and not self.dry_run:
  965. log.warn("No eggs found in %s (setup script problem?)",
  966. dist_dir)
  967. return eggs
  968. finally:
  969. rmtree(dist_dir)
  970. log.set_verbosity(self.verbose) # restore our log verbosity
  971. def _set_fetcher_options(self, base):
  972. """
  973. When easy_install is about to run bdist_egg on a source dist, that
  974. source dist might have 'setup_requires' directives, requiring
  975. additional fetching. Ensure the fetcher options given to easy_install
  976. are available to that command as well.
  977. """
  978. # find the fetch options from easy_install and write them out
  979. # to the setup.cfg file.
  980. ei_opts = self.distribution.get_option_dict('easy_install').copy()
  981. fetch_directives = (
  982. 'find_links', 'site_dirs', 'index_url', 'optimize',
  983. 'site_dirs', 'allow_hosts',
  984. )
  985. fetch_options = {}
  986. for key, val in ei_opts.iteritems():
  987. if key not in fetch_directives: continue
  988. fetch_options[key.replace('_', '-')] = val[1]
  989. # create a settings dictionary suitable for `edit_config`
  990. settings = dict(easy_install=fetch_options)
  991. cfg_filename = os.path.join(base, 'setup.cfg')
  992. setopt.edit_config(cfg_filename, settings)
  993. def update_pth(self,dist):
  994. if self.pth_file is None:
  995. return
  996. for d in self.pth_file[dist.key]: # drop old entries
  997. if self.multi_version or d.location != dist.location:
  998. log.info("Removing %s from easy-install.pth file", d)
  999. self.pth_file.remove(d)
  1000. if d.location in self.shadow_path:
  1001. self.shadow_path.remove(d.location)
  1002. if not self.multi_version:
  1003. if dist.location in self.pth_file.paths:
  1004. log.info(
  1005. "%s is already the active version in easy-install.pth",
  1006. dist
  1007. )
  1008. else:
  1009. log.info("Adding %s to easy-install.pth file", dist)
  1010. self.pth_file.add(dist) # add new entry
  1011. if dist.location not in self.shadow_path:
  1012. self.shadow_path.append(dist.location)
  1013. if not self.dry_run:
  1014. self.pth_file.save()
  1015. if dist.key=='distribute':
  1016. # Ensure that setuptools itself never becomes unavailable!
  1017. # XXX should this check for latest version?
  1018. filename = os.path.join(self.install_dir,'setuptools.pth')
  1019. if os.path.islink(filename): os.unlink(filename)
  1020. f = open(filename, 'wt')
  1021. f.write(self.pth_file.make_relative(dist.location)+'\n')
  1022. f.close()
  1023. def unpack_progress(self, src, dst):
  1024. # Progress filter for unpacking
  1025. log.debug("Unpacking %s to %s", src, dst)
  1026. return dst # only unpack-and-compile skips files for dry run
  1027. def unpack_and_compile(self, egg_path, destination):
  1028. to_compile = []; to_chmod = []
  1029. def pf(src,dst):
  1030. if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
  1031. to_compile.append(dst)
  1032. to_chmod.append(dst)
  1033. elif dst.endswith('.dll') or dst.endswith('.so'):
  1034. to_chmod.append(dst)
  1035. self.unpack_progress(src,dst)
  1036. return not self.dry_run and dst or None
  1037. unpack_archive(egg_path, destination, pf)
  1038. self.byte_compile(to_compile)
  1039. if not self.dry_run:
  1040. for f in to_chmod:
  1041. mode = ((os.stat(f)[stat.ST_MODE]) | 0555) & 07755
  1042. chmod(f, mode)
  1043. def byte_compile(self, to_compile):
  1044. if _dont_write_bytecode:
  1045. self.warn('byte-compiling is disabled, skipping.')
  1046. return
  1047. from distutils.util import byte_compile
  1048. try:
  1049. # try to make the byte compile messages quieter
  1050. log.set_verbosity(self.verbose - 1)
  1051. byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
  1052. if self.optimize:
  1053. byte_compile(
  1054. to_compile, optimize=self.optimize, force=1,
  1055. dry_run=self.dry_run
  1056. )
  1057. finally:
  1058. log.set_verbosity(self.verbose) # restore original verbosity
  1059. def no_default_version_msg(self):
  1060. return """bad install directory or PYTHONPATH
  1061. You are attempting to install a package to a directory that is not
  1062. on PYTHONPATH and which Python does not read ".pth" files from. The
  1063. installation directory you specified (via --install-dir, --prefix, or
  1064. the distutils default setting) was:
  1065. %s
  1066. and your PYTHONPATH environment variable currently contains:
  1067. %r
  1068. Here are some of your options for correcting the problem:
  1069. * You can choose a different installation directory, i.e., one that is
  1070. on PYTHONPATH or supports .pth files
  1071. * You can add the installation directory to the PYTHONPATH environment
  1072. variable. (It must then also be on PYTHONPATH whenever you run
  1073. Python and want to use the package(s) you are installing.)
  1074. * You can set up the installation directory to support ".pth" files by
  1075. using one of the approaches described here:
  1076. http://packages.python.org/distribute/easy_install.html#custom-installation-locations
  1077. Please make the appropriate changes for your system and try again.""" % (
  1078. self.install_dir, os.environ.get('PYTHONPATH','')
  1079. )
  1080. def install_site_py(self):
  1081. """Make sure there's a site.py in the target dir, if needed"""
  1082. if self.sitepy_installed:
  1083. return # already did it, or don't need to
  1084. sitepy = os.path.join(self.install_dir, "site.py")
  1085. source = resource_string(Requirement.parse("distribute"), "site.py")
  1086. current = ""
  1087. if os.path.exists(sitepy):
  1088. log.debug("Checking existing site.py in %s", self.install_dir)
  1089. f = open(sitepy,'rb')
  1090. current = f.read()
  1091. # we want str, not bytes
  1092. if sys.version_info >= (3,):
  1093. current = current.decode()
  1094. f.close()
  1095. if not current.startswith('def __boot():'):
  1096. raise DistutilsError(
  1097. "%s is not a setuptools-generated site.py; please"
  1098. " remove it." % sitepy
  1099. )
  1100. if current != source:
  1101. log.info("Creating %s", sitepy)
  1102. if not self.dry_run:
  1103. ensure_directory(sitepy)
  1104. f = open(sitepy,'wb')
  1105. f.write(source)
  1106. f.close()
  1107. self.byte_compile([sitepy])
  1108. self.sitepy_installed = True
  1109. def create_home_path(self):
  1110. """Create directories under ~."""
  1111. if not self.user:
  1112. return
  1113. home = convert_path(os.path.expanduser("~"))
  1114. for name, path in self.config_vars.iteritems():
  1115. if path.startswith(home) and not os.path.isdir(path):
  1116. self.debug_print("os.makedirs('%s', 0700)" % path)
  1117. os.makedirs(path, 0700)
  1118. INSTALL_SCHEMES = dict(
  1119. posix = dict(
  1120. install_dir = '$base/lib/python$py_version_short/site-packages',
  1121. script_dir = '$base/bin',
  1122. ),
  1123. )
  1124. DEFAULT_SCHEME = dict(
  1125. install_dir = '$base/Lib/site-packages',
  1126. script_dir = '$base/Scripts',
  1127. )
  1128. def _expand(self, *attrs):
  1129. config_vars = self.get_finalized_command('install').config_vars
  1130. if self.prefix:
  1131. # Set default install_dir/scripts from --prefix
  1132. config_vars = config_vars.copy()
  1133. config_vars['base'] = self.prefix
  1134. scheme = self.INSTALL_SCHEMES.get(os.name,self.DEFAULT_SCHEME)
  1135. for attr,val in scheme.items():
  1136. if getattr(self,attr,None) is None:
  1137. setattr(self,attr,val)
  1138. from distutils.util import subst_vars
  1139. for attr in attrs:
  1140. val = getattr(self, attr)
  1141. if val is not None:
  1142. val = subst_vars(val, config_vars)
  1143. if os.name == 'posix':
  1144. val = os.path.expanduser(val)
  1145. setattr(self, attr, val)
  1146. def get_site_dirs():
  1147. # return a list of 'site' dirs
  1148. sitedirs = filter(None,os.environ.get('PYTHONPATH','').split(os.pathsep))
  1149. prefixes = [sys.prefix]
  1150. if sys.exec_prefix != sys.prefix:
  1151. prefixes.append(sys.exec_prefix)
  1152. for prefix in prefixes:
  1153. if prefix:
  1154. if sys.platform in ('os2emx', 'riscos'):
  1155. sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  1156. elif os.sep == '/':
  1157. sitedirs.extend([os.path.join(prefix,
  1158. "lib",
  1159. "python" + sys.version[:3],
  1160. "site-packages"),
  1161. os.path.join(prefix, "lib", "site-python")])
  1162. else:
  1163. sitedirs.extend(
  1164. [prefix, os.path.join(prefix, "lib", "site-packages")]
  1165. )
  1166. if sys.platform == 'darwin':
  1167. # for framework builds *only* we add the standard Apple
  1168. # locations. Currently only per-user, but /Library and
  1169. # /Network/Library could be added too
  1170. if 'Python.framework' in prefix:
  1171. home = os.environ.get('HOME')
  1172. if home:
  1173. sitedirs.append(
  1174. os.path.join(home,
  1175. 'Library',
  1176. 'Python',
  1177. sys.version[:3],
  1178. 'site-packages'))
  1179. for plat_specific in (0,1):
  1180. site_lib = get_python_lib(plat_specific)
  1181. if site_lib not in sitedirs: sitedirs.append(site_lib)
  1182. if HAS_USER_SITE:
  1183. sitedirs.append(site.USER_SITE)
  1184. sitedirs = map(normalize_path, sitedirs)
  1185. return sitedirs
  1186. def expand_paths(inputs):
  1187. """Yield sys.path directories that might contain "old-style" packages"""
  1188. seen = {}
  1189. for dirname in inputs:
  1190. dirname = normalize_path(dirname)
  1191. if dirname in seen:
  1192. continue
  1193. seen[dirname] = 1
  1194. if not os.path.isdir(dirname):
  1195. continue
  1196. files = os.listdir(dirname)
  1197. yield dirname, files
  1198. for name in files:
  1199. if not name.endswith('.pth'):
  1200. # We only care about the .pth files
  1201. continue
  1202. if name in ('easy-install.pth','setuptools.pth'):
  1203. # Ignore .pth files that we control
  1204. continue
  1205. # Read the .pth file
  1206. f = open(os.path.join(dirname,name))
  1207. lines = list(yield_lines(f))
  1208. f.close()
  1209. # Yield existing non-dupe, non-import directory lines from it
  1210. for line in lines:
  1211. if not line.startswith("import"):
  1212. line = normalize_path(line.rstrip())
  1213. if line not in seen:
  1214. seen[line] = 1
  1215. if not os.path.isdir(line):
  1216. continue
  1217. yield line, os.listdir(line)
  1218. def extract_wininst_cfg(dist_filename):
  1219. """Extract configuration data from a bdist_wininst .exe
  1220. Returns a ConfigParser.RawConfigParser, or None
  1221. """
  1222. f = open(dist_filename,'rb')
  1223. try:
  1224. endrec = zipfile._EndRecData(f)
  1225. if endrec is None:
  1226. return None
  1227. prepended = (endrec[9] - endrec[5]) - endrec[6]
  1228. if prepended < 12: # no wininst data here
  1229. return None
  1230. f.seek(prepended-12)
  1231. import struct, StringIO, ConfigParser
  1232. tag, cfglen, bmlen = struct.unpack("<iii",f.read(12))
  1233. if tag not in (0x1234567A, 0x1234567B):
  1234. return None # not a valid tag
  1235. f.seek(prepended-(12+cfglen))
  1236. cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
  1237. try:
  1238. part = f.read(cfglen)
  1239. # part is in bytes, but we need to read up to the first null
  1240. # byte.
  1241. if sys.version_info >= (2,6):
  1242. null_byte = bytes([0])
  1243. else:
  1244. null_byte = chr(0)
  1245. config = part.split(null_byte, 1)[0]
  1246. # Now the config is in bytes, but on Python 3, it must be
  1247. # unicode for the RawConfigParser, so decode it. Is this the
  1248. # right encoding?
  1249. config = config.decode('ascii')
  1250. cfg.readfp(StringIO.StringIO(config))
  1251. except ConfigParser.Error:
  1252. return None
  1253. if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
  1254. return None
  1255. return cfg
  1256. finally:
  1257. f.close()
  1258. def get_exe_prefixes(exe_filename):
  1259. """Get exe->egg path translations for a given .exe file"""
  1260. prefixes = [
  1261. ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
  1262. ('PLATLIB/', ''),
  1263. ('SCRIPTS/', 'EGG-INFO/scripts/'),
  1264. ('DATA/LIB/site-packages', ''),
  1265. ]
  1266. z = zipfile.ZipFile(exe_filename)
  1267. try:
  1268. for info in z.infolist():
  1269. name = info.filename
  1270. parts = name.split('/')
  1271. if len(parts)==3 and parts[2]=='PKG-INFO':
  1272. if parts[1].endswith('.egg-info'):
  1273. prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))
  1274. break
  1275. if len(parts)<>2 or not name.endswith('.pth'):
  1276. continue
  1277. if name.endswith('-nspkg.pth'):
  1278. continue
  1279. if parts[0].upper() in ('PURELIB','PLATLIB'):
  1280. for pth in yield_lines(z.read(name)):
  1281. pth = pth.strip().replace('\\','/')
  1282. if not pth.startswith('import'):
  1283. prefixes.append((('%s/%s/' % (parts[0],pth)), ''))
  1284. finally:
  1285. z.close()
  1286. prefixes = [(x.lower(),y) for x, y in prefixes]
  1287. prefixes.sort(); prefixes.reverse()
  1288. return prefixes
  1289. def parse_requirement_arg(spec):
  1290. try:
  1291. return Requirement.parse(spec)
  1292. except ValueError:
  1293. raise DistutilsError(
  1294. "Not a URL, existing file, or requirement spec: %r" % (spec,)
  1295. )
  1296. class PthDistributions(Environment):
  1297. """A .pth file with Distribution paths in it"""
  1298. dirty = False
  1299. def __init__(self, filename, sitedirs=()):
  1300. self.filename = filename; self.sitedirs=map(normalize_path, sitedirs)
  1301. self.basedir = normalize_path(os.path.dirname(self.filename))
  1302. self._load(); Environment.__init__(self, [], None, None)
  1303. for path in yield_lines(self.paths):
  1304. map(self.add, find_distributions(path, True))
  1305. def _load(self):
  1306. self.paths = []
  1307. saw_import = False
  1308. seen = dict.fromkeys(self.sitedirs)
  1309. if os.path.isfile(self.filename):
  1310. f = open(self.filename,'rt')
  1311. for line in f:
  1312. if line.startswith('import'):
  1313. saw_import = True
  1314. continue
  1315. path = line.rstrip()
  1316. self.paths.append(path)
  1317. if not path.strip() or path.strip().startswith('#'):
  1318. continue
  1319. # skip non-existent paths, in case somebody deleted a package
  1320. # manually, and duplicate paths as well
  1321. path = self.paths[-1] = normalize_path(
  1322. os.path.join(self.basedir,path)
  1323. )
  1324. if not os.path.exists(path) or path in seen:
  1325. self.paths.pop() # skip it
  1326. self.dirty = True # we cleaned up, so we're dirty now :)
  1327. continue
  1328. seen[path] = 1
  1329. f.close()
  1330. if self.paths and not saw_import:
  1331. self.dirty = True # ensure anything we touch has import wrappers
  1332. while self.paths and not self.paths[-1].strip():
  1333. self.paths.pop()
  1334. def save(self):
  1335. """Write changed .pth file back to disk"""
  1336. if not self.dirty:
  1337. return
  1338. data = '\n'.join(map(self.make_relative,self.paths))
  1339. if data:
  1340. log.debug("Saving %s", self.filename)
  1341. data = (
  1342. "import sys; sys.__plen = len(sys.path)\n"
  1343. "%s\n"
  1344. "import sys; new=sys.path[sys.__plen:];"
  1345. " del sys.path[sys.__plen:];"
  1346. " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;"
  1347. " sys.__egginsert = p+len(new)\n"
  1348. ) % data
  1349. if os.path.islink(self.filename):
  1350. os.unlink(self.filename)
  1351. f = open(self.filename,'wt')
  1352. f.write(data); f.close()
  1353. elif os.path.exists(self.filename):
  1354. log.debug("Deleting empty %s", self.filename)
  1355. os.unlink(self.filename)
  1356. self.dirty = False
  1357. def add(self,dist):
  1358. """Add `dist` to the distribution map"""
  1359. if (dist.location not in self.paths and (
  1360. dist.location not in self.sitedirs or
  1361. dist.location == os.getcwd() #account for '.' being in PYTHONPATH
  1362. )):
  1363. self.paths.append(dist.location)
  1364. self.dirty = True
  1365. Environment.add(self,dist)
  1366. def remove(self,dist):
  1367. """Remove `dist` from the distribution map"""
  1368. while dist.location in self.paths:
  1369. self.paths.remove(dist.location); self.dirty = True
  1370. Environment.remove(self,dist)
  1371. def make_relative(self,path):
  1372. npath, last = os.path.split(normalize_path(path))
  1373. baselen = len(self.basedir)
  1374. parts = [last]
  1375. sep = os.altsep=='/' and '/' or os.sep
  1376. while len(npath)>=baselen:
  1377. if npath==self.basedir:
  1378. parts.append(os.curdir)
  1379. parts.reverse()
  1380. return sep.join(parts)
  1381. npath, last = os.path.split(npath)
  1382. parts.append(last)
  1383. else:
  1384. return path
  1385. def get_script_header(script_text, executable=sys_executable, wininst=False):
  1386. """Create a #! line, getting options (if any) from script_text"""
  1387. from distutils.command.build_scripts import first_line_re
  1388. # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
  1389. if not isinstance(first_line_re.pattern, str):
  1390. first_line_re = re.compile(first_line_re.pattern.decode())
  1391. first = (script_text+'\n').splitlines()[0]
  1392. match = first_line_re.match(first)
  1393. options = ''
  1394. if match:
  1395. options = match.group(1) or ''
  1396. if options: options = ' '+options
  1397. if wininst:
  1398. executable = "python.exe"
  1399. else:
  1400. executable = nt_quote_arg(executable)
  1401. hdr = "#!%(executable)s%(options)s\n" % locals()
  1402. if not isascii(hdr):
  1403. # Non-ascii path to sys.executable, use -x to prevent warnings
  1404. if options:
  1405. if options.strip().startswith('-'):
  1406. options = ' -x'+options.strip()[1:]
  1407. # else: punt, we can't do it, let the warning happen anyway
  1408. else:
  1409. options = ' -x'
  1410. executable = fix_jython_executable(executable, options)
  1411. hdr = "#!%(executable)s%(options)s\n" % locals()
  1412. return hdr
  1413. def auto_chmod(func, arg, exc):
  1414. if func is os.remove and os.name=='nt':
  1415. chmod(arg, stat.S_IWRITE)
  1416. return func(arg)
  1417. exc = sys.exc_info()
  1418. raise exc[0], (exc[1][0], exc[1][1] + (" %s %s" % (func,arg)))
  1419. def uncache_zipdir(path):
  1420. """Ensure that the importer caches dont have stale info for `path`"""
  1421. from zipimport import _zip_directory_cache as zdc
  1422. _uncache(path, zdc)
  1423. _uncache(path, sys.path_importer_cache)
  1424. def _uncache(path, cache):
  1425. if path in cache:
  1426. del cache[path]
  1427. else:
  1428. path = normalize_path(path)
  1429. for p in cache:
  1430. if normalize_path(p)==path:
  1431. del cache[p]
  1432. return
  1433. def is_python(text, filename='<string>'):
  1434. "Is this string a valid Python script?"
  1435. try:
  1436. compile(text, filename, 'exec')
  1437. except (SyntaxError, TypeError):
  1438. return False
  1439. else:
  1440. return True
  1441. def is_sh(executable):
  1442. """Determine if the specified executable is a .sh (contains a #! line)"""
  1443. try:
  1444. fp = open(executable)
  1445. magic = fp.read(2)
  1446. fp.close()
  1447. except (OSError,IOError): return executable
  1448. return magic == '#!'
  1449. def nt_quote_arg(arg):
  1450. """Quote a command line argument according to Windows parsing rules"""
  1451. result = []
  1452. needquote = False
  1453. nb = 0
  1454. needquote = (" " in arg) or ("\t" in arg)
  1455. if needquote:
  1456. result.append('"')
  1457. for c in arg:
  1458. if c == '\\':
  1459. nb += 1
  1460. elif c == '"':
  1461. # double preceding backslashes, then add a \"
  1462. result.append('\\' * (nb*2) + '\\"')
  1463. nb = 0
  1464. else:
  1465. if nb:
  1466. result.append('\\' * nb)
  1467. nb = 0
  1468. result.append(c)
  1469. if nb:
  1470. result.append('\\' * nb)
  1471. if needquote:
  1472. result.append('\\' * nb) # double the trailing backslashes
  1473. result.append('"')
  1474. return ''.join(result)
  1475. def is_python_script(script_text, filename):
  1476. """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
  1477. """
  1478. if filename.endswith('.py') or filename.endswith('.pyw'):
  1479. return True # extension says it's Python
  1480. if is_python(script_text, filename):
  1481. return True # it's syntactically valid Python
  1482. if script_text.startswith('#!'):
  1483. # It begins with a '#!' line, so check if 'python' is in it somewhere
  1484. return 'python' in script_text.splitlines()[0].lower()
  1485. return False # Not any Python I can recognize
  1486. try:
  1487. from os import chmod as _chmod
  1488. except ImportError:
  1489. # Jython compatibility
  1490. def _chmod(*args): pass
  1491. def chmod(path, mode):
  1492. log.debug("changing mode of %s to %o", path, mode)
  1493. try:
  1494. _chmod(path, mode)
  1495. except os.error, e:
  1496. log.debug("chmod failed: %s", e)
  1497. def fix_jython_executable(executable, options):
  1498. if sys.platform.startswith('java') and is_sh(executable):
  1499. # Workaround Jython's sys.executable being a .sh (an invalid
  1500. # shebang line interpreter)
  1501. if options:
  1502. # Can't apply the workaround, leave it broken
  1503. log.warn("WARNING: Unable to adapt shebang line for Jython,"
  1504. " the following script is NOT executable\n"
  1505. " see http://bugs.jython.org/issue1112 for"
  1506. " more information.")
  1507. else:
  1508. return '/usr/bin/env %s' % executable
  1509. return executable
  1510. def get_script_args(dist, executable=sys_executable, wininst=False):
  1511. """Yield write_script() argument tuples for a distribution's entrypoints"""
  1512. spec = str(dist.as_requirement())
  1513. header = get_script_header("", executable, wininst)
  1514. for group in 'console_scripts', 'gui_scripts':
  1515. for name, ep in dist.get_entry_map(group).items():
  1516. script_text = (
  1517. "# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n"
  1518. "__requires__ = %(spec)r\n"
  1519. "import sys\n"
  1520. "from pkg_resources import load_entry_point\n"
  1521. "\n"
  1522. "if __name__ == '__main__':"
  1523. "\n"
  1524. " sys.exit(\n"
  1525. " load_entry_point(%(spec)r, %(group)r, %(name)r)()\n"
  1526. " )\n"
  1527. ) % locals()
  1528. if sys.platform=='win32' or wininst:
  1529. # On Windows/wininst, add a .py extension and an .exe launcher
  1530. if group=='gui_scripts':
  1531. ext, launcher = '-script.pyw', 'gui.exe'
  1532. old = ['.pyw']
  1533. new_header = re.sub('(?i)python.exe','pythonw.exe',header)
  1534. else:
  1535. ext, launcher = '-script.py', 'cli.exe'
  1536. old = ['.py','.pyc','.pyo']
  1537. new_header = re.sub('(?i)pythonw.exe','python.exe',header)
  1538. if is_64bit():
  1539. launcher = launcher.replace(".", "-64.")
  1540. else:
  1541. launcher = launcher.replace(".", "-32.")
  1542. if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
  1543. hdr = new_header
  1544. else:
  1545. hdr = header
  1546. yield (name+ext, hdr+script_text, 't', [name+x for x in old])
  1547. yield (
  1548. name+'.exe', resource_string('setuptools', launcher),
  1549. 'b' # write in binary mode
  1550. )
  1551. else:
  1552. # On other platforms, we assume the right thing to do is to
  1553. # just write the stub with no extension.
  1554. yield (name, header+script_text)
  1555. def rmtree(path, ignore_errors=False, onerror=auto_chmod):
  1556. """Recursively delete a directory tree.
  1557. This code is taken from the Python 2.4 version of 'shutil', because
  1558. the 2.3 version doesn't really work right.
  1559. """
  1560. if ignore_errors:
  1561. def onerror(*args):
  1562. pass
  1563. elif onerror is None:
  1564. def onerror(*args):
  1565. raise
  1566. names = []
  1567. try:
  1568. names = os.listdir(path)
  1569. except os.error, err:
  1570. onerror(os.listdir, path, sys.exc_info())
  1571. for name in names:
  1572. fullname = os.path.join(path, name)
  1573. try:
  1574. mode = os.lstat(fullname).st_mode
  1575. except os.error:
  1576. mode = 0
  1577. if stat.S_ISDIR(mode):
  1578. rmtree(fullname, ignore_errors, onerror)
  1579. else:
  1580. try:
  1581. os.remove(fullname)
  1582. except os.error, err:
  1583. onerror(os.remove, fullname, sys.exc_info())
  1584. try:
  1585. os.rmdir(path)
  1586. except os.error:
  1587. onerror(os.rmdir, path, sys.exc_info())
  1588. def current_umask():
  1589. tmp = os.umask(022)
  1590. os.umask(tmp)
  1591. return tmp
  1592. def bootstrap():
  1593. # This function is called when setuptools*.egg is run using /bin/sh
  1594. import setuptools; argv0 = os.path.dirname(setuptools.__path__[0])
  1595. sys.argv[0] = argv0; sys.argv.append(argv0); main()
  1596. def main(argv=None, **kw):
  1597. from setuptools import setup
  1598. from setuptools.dist import Distribution
  1599. import distutils.core
  1600. USAGE = """\
  1601. usage: %(script)s [options] requirement_or_url ...
  1602. or: %(script)s --help
  1603. """
  1604. def gen_usage (script_name):
  1605. script = os.path.basename(script_name)
  1606. return USAGE % vars()
  1607. def with_ei_usage(f):
  1608. old_gen_usage = distutils.core.gen_usage
  1609. try:
  1610. distutils.core.gen_usage = gen_usage
  1611. return f()
  1612. finally:
  1613. distutils.core.gen_usage = old_gen_usage
  1614. class DistributionWithoutHelpCommands(Distribution):
  1615. common_usage = ""
  1616. def _show_help(self,*args,**kw):
  1617. with_ei_usage(lambda: Distribution._show_help(self,*args,**kw))
  1618. def find_config_files(self):
  1619. files = Distribution.find_config_files(self)
  1620. if 'setup.cfg' in files:
  1621. files.remove('setup.cfg')
  1622. return files
  1623. if argv is None:
  1624. argv = sys.argv[1:]
  1625. with_ei_usage(lambda:
  1626. setup(
  1627. script_args = ['-q','easy_install', '-v']+argv,
  1628. script_name = sys.argv[0] or 'easy_install',
  1629. distclass=DistributionWithoutHelpCommands, **kw
  1630. )
  1631. )