PageRenderTime 60ms CodeModel.GetById 21ms 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

Large files files are truncated, but you can click here to view the full 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

Large files files are truncated, but you can click here to view the full file