You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2268 lines
84 KiB

  1. #!/usr/bin/env 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. __ https://pythonhosted.org/setuptools/easy_install.html
  9. """
  10. from glob import glob
  11. from distutils.util import get_platform
  12. from distutils.util import convert_path, subst_vars
  13. from distutils.errors import DistutilsArgError, DistutilsOptionError, \
  14. DistutilsError, DistutilsPlatformError
  15. from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
  16. from distutils import log, dir_util
  17. from distutils.command.build_scripts import first_line_re
  18. import sys
  19. import os
  20. import zipimport
  21. import shutil
  22. import tempfile
  23. import zipfile
  24. import re
  25. import stat
  26. import random
  27. import platform
  28. import textwrap
  29. import warnings
  30. import site
  31. import struct
  32. import contextlib
  33. import subprocess
  34. import shlex
  35. import io
  36. from setuptools import Command
  37. from setuptools.sandbox import run_setup
  38. from setuptools.py31compat import get_path, get_config_vars
  39. from setuptools.command import setopt
  40. from setuptools.archive_util import unpack_archive
  41. from setuptools.package_index import PackageIndex
  42. from setuptools.package_index import URL_SCHEME
  43. from setuptools.command import bdist_egg, egg_info
  44. from setuptools.compat import (iteritems, maxsize, basestring, unicode,
  45. reraise, PY2, PY3)
  46. from pkg_resources import (
  47. yield_lines, normalize_path, resource_string, ensure_directory,
  48. get_distribution, find_distributions, Environment, Requirement,
  49. Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
  50. VersionConflict, DEVELOP_DIST,
  51. )
  52. import pkg_resources
  53. # Turn on PEP440Warnings
  54. warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
  55. __all__ = [
  56. 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
  57. 'main', 'get_exe_prefixes',
  58. ]
  59. def is_64bit():
  60. return struct.calcsize("P") == 8
  61. def samefile(p1, p2):
  62. both_exist = os.path.exists(p1) and os.path.exists(p2)
  63. use_samefile = hasattr(os.path, 'samefile') and both_exist
  64. if use_samefile:
  65. return os.path.samefile(p1, p2)
  66. norm_p1 = os.path.normpath(os.path.normcase(p1))
  67. norm_p2 = os.path.normpath(os.path.normcase(p2))
  68. return norm_p1 == norm_p2
  69. if PY2:
  70. def _to_ascii(s):
  71. return s
  72. def isascii(s):
  73. try:
  74. unicode(s, 'ascii')
  75. return True
  76. except UnicodeError:
  77. return False
  78. else:
  79. def _to_ascii(s):
  80. return s.encode('ascii')
  81. def isascii(s):
  82. try:
  83. s.encode('ascii')
  84. return True
  85. except UnicodeError:
  86. return False
  87. class easy_install(Command):
  88. """Manage a download/build/install process"""
  89. description = "Find/get/install Python packages"
  90. command_consumes_arguments = True
  91. user_options = [
  92. ('prefix=', None, "installation prefix"),
  93. ("zip-ok", "z", "install package as a zipfile"),
  94. ("multi-version", "m", "make apps have to require() a version"),
  95. ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
  96. ("install-dir=", "d", "install package to DIR"),
  97. ("script-dir=", "s", "install scripts to DIR"),
  98. ("exclude-scripts", "x", "Don't install scripts"),
  99. ("always-copy", "a", "Copy all needed packages to install dir"),
  100. ("index-url=", "i", "base URL of Python Package Index"),
  101. ("find-links=", "f", "additional URL(s) to search for packages"),
  102. ("build-directory=", "b",
  103. "download/extract/build in DIR; keep the results"),
  104. ('optimize=', 'O',
  105. "also compile with optimization: -O1 for \"python -O\", "
  106. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  107. ('record=', None,
  108. "filename in which to record list of installed files"),
  109. ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
  110. ('site-dirs=', 'S', "list of directories where .pth files work"),
  111. ('editable', 'e', "Install specified packages in editable form"),
  112. ('no-deps', 'N', "don't install dependencies"),
  113. ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
  114. ('local-snapshots-ok', 'l',
  115. "allow building eggs from local checkouts"),
  116. ('version', None, "print version information and exit"),
  117. ('no-find-links', None,
  118. "Don't load find-links defined in packages being installed")
  119. ]
  120. boolean_options = [
  121. 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
  122. 'editable',
  123. 'no-deps', 'local-snapshots-ok', 'version'
  124. ]
  125. if site.ENABLE_USER_SITE:
  126. help_msg = "install in user site-package '%s'" % site.USER_SITE
  127. user_options.append(('user', None, help_msg))
  128. boolean_options.append('user')
  129. negative_opt = {'always-unzip': 'zip-ok'}
  130. create_index = PackageIndex
  131. def initialize_options(self):
  132. # the --user option seems to be an opt-in one,
  133. # so the default should be False.
  134. self.user = 0
  135. self.zip_ok = self.local_snapshots_ok = None
  136. self.install_dir = self.script_dir = self.exclude_scripts = None
  137. self.index_url = None
  138. self.find_links = None
  139. self.build_directory = None
  140. self.args = None
  141. self.optimize = self.record = None
  142. self.upgrade = self.always_copy = self.multi_version = None
  143. self.editable = self.no_deps = self.allow_hosts = None
  144. self.root = self.prefix = self.no_report = None
  145. self.version = None
  146. self.install_purelib = None # for pure module distributions
  147. self.install_platlib = None # non-pure (dists w/ extensions)
  148. self.install_headers = None # for C/C++ headers
  149. self.install_lib = None # set to either purelib or platlib
  150. self.install_scripts = None
  151. self.install_data = None
  152. self.install_base = None
  153. self.install_platbase = None
  154. if site.ENABLE_USER_SITE:
  155. self.install_userbase = site.USER_BASE
  156. self.install_usersite = site.USER_SITE
  157. else:
  158. self.install_userbase = None
  159. self.install_usersite = None
  160. self.no_find_links = None
  161. # Options not specifiable via command line
  162. self.package_index = None
  163. self.pth_file = self.always_copy_from = None
  164. self.site_dirs = None
  165. self.installed_projects = {}
  166. self.sitepy_installed = False
  167. # Always read easy_install options, even if we are subclassed, or have
  168. # an independent instance created. This ensures that defaults will
  169. # always come from the standard configuration file(s)' "easy_install"
  170. # section, even if this is a "develop" or "install" command, or some
  171. # other embedding.
  172. self._dry_run = None
  173. self.verbose = self.distribution.verbose
  174. self.distribution._set_command_options(
  175. self, self.distribution.get_option_dict('easy_install')
  176. )
  177. def delete_blockers(self, blockers):
  178. extant_blockers = (
  179. filename for filename in blockers
  180. if os.path.exists(filename) or os.path.islink(filename)
  181. )
  182. list(map(self._delete_path, extant_blockers))
  183. def _delete_path(self, path):
  184. log.info("Deleting %s", path)
  185. if self.dry_run:
  186. return
  187. is_tree = os.path.isdir(path) and not os.path.islink(path)
  188. remover = rmtree if is_tree else os.unlink
  189. remover(path)
  190. def finalize_options(self):
  191. if self.version:
  192. print('setuptools %s' % get_distribution('setuptools').version)
  193. sys.exit()
  194. py_version = sys.version.split()[0]
  195. prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
  196. self.config_vars = {
  197. 'dist_name': self.distribution.get_name(),
  198. 'dist_version': self.distribution.get_version(),
  199. 'dist_fullname': self.distribution.get_fullname(),
  200. 'py_version': py_version,
  201. 'py_version_short': py_version[0:3],
  202. 'py_version_nodot': py_version[0] + py_version[2],
  203. 'sys_prefix': prefix,
  204. 'prefix': prefix,
  205. 'sys_exec_prefix': exec_prefix,
  206. 'exec_prefix': exec_prefix,
  207. # Only python 3.2+ has abiflags
  208. 'abiflags': getattr(sys, 'abiflags', ''),
  209. }
  210. if site.ENABLE_USER_SITE:
  211. self.config_vars['userbase'] = self.install_userbase
  212. self.config_vars['usersite'] = self.install_usersite
  213. self._fix_install_dir_for_user_site()
  214. self.expand_basedirs()
  215. self.expand_dirs()
  216. self._expand('install_dir', 'script_dir', 'build_directory',
  217. 'site_dirs')
  218. # If a non-default installation directory was specified, default the
  219. # script directory to match it.
  220. if self.script_dir is None:
  221. self.script_dir = self.install_dir
  222. if self.no_find_links is None:
  223. self.no_find_links = False
  224. # Let install_dir get set by install_lib command, which in turn
  225. # gets its info from the install command, and takes into account
  226. # --prefix and --home and all that other crud.
  227. self.set_undefined_options(
  228. 'install_lib', ('install_dir', 'install_dir')
  229. )
  230. # Likewise, set default script_dir from 'install_scripts.install_dir'
  231. self.set_undefined_options(
  232. 'install_scripts', ('install_dir', 'script_dir')
  233. )
  234. if self.user and self.install_purelib:
  235. self.install_dir = self.install_purelib
  236. self.script_dir = self.install_scripts
  237. # default --record from the install command
  238. self.set_undefined_options('install', ('record', 'record'))
  239. # Should this be moved to the if statement below? It's not used
  240. # elsewhere
  241. normpath = map(normalize_path, sys.path)
  242. self.all_site_dirs = get_site_dirs()
  243. if self.site_dirs is not None:
  244. site_dirs = [
  245. os.path.expanduser(s.strip()) for s in
  246. self.site_dirs.split(',')
  247. ]
  248. for d in site_dirs:
  249. if not os.path.isdir(d):
  250. log.warn("%s (in --site-dirs) does not exist", d)
  251. elif normalize_path(d) not in normpath:
  252. raise DistutilsOptionError(
  253. d + " (in --site-dirs) is not on sys.path"
  254. )
  255. else:
  256. self.all_site_dirs.append(normalize_path(d))
  257. if not self.editable:
  258. self.check_site_dir()
  259. self.index_url = self.index_url or "https://pypi.python.org/simple"
  260. self.shadow_path = self.all_site_dirs[:]
  261. for path_item in self.install_dir, normalize_path(self.script_dir):
  262. if path_item not in self.shadow_path:
  263. self.shadow_path.insert(0, path_item)
  264. if self.allow_hosts is not None:
  265. hosts = [s.strip() for s in self.allow_hosts.split(',')]
  266. else:
  267. hosts = ['*']
  268. if self.package_index is None:
  269. self.package_index = self.create_index(
  270. self.index_url, search_path=self.shadow_path, hosts=hosts,
  271. )
  272. self.local_index = Environment(self.shadow_path + sys.path)
  273. if self.find_links is not None:
  274. if isinstance(self.find_links, basestring):
  275. self.find_links = self.find_links.split()
  276. else:
  277. self.find_links = []
  278. if self.local_snapshots_ok:
  279. self.package_index.scan_egg_links(self.shadow_path + sys.path)
  280. if not self.no_find_links:
  281. self.package_index.add_find_links(self.find_links)
  282. self.set_undefined_options('install_lib', ('optimize', 'optimize'))
  283. if not isinstance(self.optimize, int):
  284. try:
  285. self.optimize = int(self.optimize)
  286. if not (0 <= self.optimize <= 2):
  287. raise ValueError
  288. except ValueError:
  289. raise DistutilsOptionError("--optimize must be 0, 1, or 2")
  290. if self.editable and not self.build_directory:
  291. raise DistutilsArgError(
  292. "Must specify a build directory (-b) when using --editable"
  293. )
  294. if not self.args:
  295. raise DistutilsArgError(
  296. "No urls, filenames, or requirements specified (see --help)")
  297. self.outputs = []
  298. def _fix_install_dir_for_user_site(self):
  299. """
  300. Fix the install_dir if "--user" was used.
  301. """
  302. if not self.user or not site.ENABLE_USER_SITE:
  303. return
  304. self.create_home_path()
  305. if self.install_userbase is None:
  306. msg = "User base directory is not specified"
  307. raise DistutilsPlatformError(msg)
  308. self.install_base = self.install_platbase = self.install_userbase
  309. scheme_name = os.name.replace('posix', 'unix') + '_user'
  310. self.select_scheme(scheme_name)
  311. def _expand_attrs(self, attrs):
  312. for attr in attrs:
  313. val = getattr(self, attr)
  314. if val is not None:
  315. if os.name == 'posix' or os.name == 'nt':
  316. val = os.path.expanduser(val)
  317. val = subst_vars(val, self.config_vars)
  318. setattr(self, attr, val)
  319. def expand_basedirs(self):
  320. """Calls `os.path.expanduser` on install_base, install_platbase and
  321. root."""
  322. self._expand_attrs(['install_base', 'install_platbase', 'root'])
  323. def expand_dirs(self):
  324. """Calls `os.path.expanduser` on install dirs."""
  325. self._expand_attrs(['install_purelib', 'install_platlib',
  326. 'install_lib', 'install_headers',
  327. 'install_scripts', 'install_data', ])
  328. def run(self):
  329. if self.verbose != self.distribution.verbose:
  330. log.set_verbosity(self.verbose)
  331. try:
  332. for spec in self.args:
  333. self.easy_install(spec, not self.no_deps)
  334. if self.record:
  335. outputs = self.outputs
  336. if self.root: # strip any package prefix
  337. root_len = len(self.root)
  338. for counter in range(len(outputs)):
  339. outputs[counter] = outputs[counter][root_len:]
  340. from distutils import file_util
  341. self.execute(
  342. file_util.write_file, (self.record, outputs),
  343. "writing list of installed files to '%s'" %
  344. self.record
  345. )
  346. self.warn_deprecated_options()
  347. finally:
  348. log.set_verbosity(self.distribution.verbose)
  349. def pseudo_tempname(self):
  350. """Return a pseudo-tempname base in the install directory.
  351. This code is intentionally naive; if a malicious party can write to
  352. the target directory you're already in deep doodoo.
  353. """
  354. try:
  355. pid = os.getpid()
  356. except:
  357. pid = random.randint(0, maxsize)
  358. return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
  359. def warn_deprecated_options(self):
  360. pass
  361. def check_site_dir(self):
  362. """Verify that self.install_dir is .pth-capable dir, if needed"""
  363. instdir = normalize_path(self.install_dir)
  364. pth_file = os.path.join(instdir, 'easy-install.pth')
  365. # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
  366. is_site_dir = instdir in self.all_site_dirs
  367. if not is_site_dir and not self.multi_version:
  368. # No? Then directly test whether it does .pth file processing
  369. is_site_dir = self.check_pth_processing()
  370. else:
  371. # make sure we can write to target dir
  372. testfile = self.pseudo_tempname() + '.write-test'
  373. test_exists = os.path.exists(testfile)
  374. try:
  375. if test_exists:
  376. os.unlink(testfile)
  377. open(testfile, 'w').close()
  378. os.unlink(testfile)
  379. except (OSError, IOError):
  380. self.cant_write_to_target()
  381. if not is_site_dir and not self.multi_version:
  382. # Can't install non-multi to non-site dir
  383. raise DistutilsError(self.no_default_version_msg())
  384. if is_site_dir:
  385. if self.pth_file is None:
  386. self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
  387. else:
  388. self.pth_file = None
  389. PYTHONPATH = os.environ.get('PYTHONPATH', '').split(os.pathsep)
  390. if instdir not in map(normalize_path, filter(None, PYTHONPATH)):
  391. # only PYTHONPATH dirs need a site.py, so pretend it's there
  392. self.sitepy_installed = True
  393. elif self.multi_version and not os.path.exists(pth_file):
  394. self.sitepy_installed = True # don't need site.py in this case
  395. self.pth_file = None # and don't create a .pth file
  396. self.install_dir = instdir
  397. __cant_write_msg = textwrap.dedent("""
  398. can't create or remove files in install directory
  399. The following error occurred while trying to add or remove files in the
  400. installation directory:
  401. %s
  402. The installation directory you specified (via --install-dir, --prefix, or
  403. the distutils default setting) was:
  404. %s
  405. """).lstrip()
  406. __not_exists_id = textwrap.dedent("""
  407. This directory does not currently exist. Please create it and try again, or
  408. choose a different installation directory (using the -d or --install-dir
  409. option).
  410. """).lstrip()
  411. __access_msg = textwrap.dedent("""
  412. Perhaps your account does not have write access to this directory? If the
  413. installation directory is a system-owned directory, you may need to sign in
  414. as the administrator or "root" account. If you do not have administrative
  415. access to this machine, you may wish to choose a different installation
  416. directory, preferably one that is listed in your PYTHONPATH environment
  417. variable.
  418. For information on other options, you may wish to consult the
  419. documentation at:
  420. https://pythonhosted.org/setuptools/easy_install.html
  421. Please make the appropriate changes for your system and try again.
  422. """).lstrip()
  423. def cant_write_to_target(self):
  424. msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
  425. if not os.path.exists(self.install_dir):
  426. msg += '\n' + self.__not_exists_id
  427. else:
  428. msg += '\n' + self.__access_msg
  429. raise DistutilsError(msg)
  430. def check_pth_processing(self):
  431. """Empirically verify whether .pth files are supported in inst. dir"""
  432. instdir = self.install_dir
  433. log.info("Checking .pth file support in %s", instdir)
  434. pth_file = self.pseudo_tempname() + ".pth"
  435. ok_file = pth_file + '.ok'
  436. ok_exists = os.path.exists(ok_file)
  437. try:
  438. if ok_exists:
  439. os.unlink(ok_file)
  440. dirname = os.path.dirname(ok_file)
  441. if not os.path.exists(dirname):
  442. os.makedirs(dirname)
  443. f = open(pth_file, 'w')
  444. except (OSError, IOError):
  445. self.cant_write_to_target()
  446. else:
  447. try:
  448. f.write("import os; f = open(%r, 'w'); f.write('OK'); "
  449. "f.close()\n" % (ok_file,))
  450. f.close()
  451. f = None
  452. executable = sys.executable
  453. if os.name == 'nt':
  454. dirname, basename = os.path.split(executable)
  455. alt = os.path.join(dirname, 'pythonw.exe')
  456. if (basename.lower() == 'python.exe' and
  457. os.path.exists(alt)):
  458. # use pythonw.exe to avoid opening a console window
  459. executable = alt
  460. from distutils.spawn import spawn
  461. spawn([executable, '-E', '-c', 'pass'], 0)
  462. if os.path.exists(ok_file):
  463. log.info(
  464. "TEST PASSED: %s appears to support .pth files",
  465. instdir
  466. )
  467. return True
  468. finally:
  469. if f:
  470. f.close()
  471. if os.path.exists(ok_file):
  472. os.unlink(ok_file)
  473. if os.path.exists(pth_file):
  474. os.unlink(pth_file)
  475. if not self.multi_version:
  476. log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
  477. return False
  478. def install_egg_scripts(self, dist):
  479. """Write all the scripts for `dist`, unless scripts are excluded"""
  480. if not self.exclude_scripts and dist.metadata_isdir('scripts'):
  481. for script_name in dist.metadata_listdir('scripts'):
  482. if dist.metadata_isdir('scripts/' + script_name):
  483. # The "script" is a directory, likely a Python 3
  484. # __pycache__ directory, so skip it.
  485. continue
  486. self.install_script(
  487. dist, script_name,
  488. dist.get_metadata('scripts/' + script_name)
  489. )
  490. self.install_wrapper_scripts(dist)
  491. def add_output(self, path):
  492. if os.path.isdir(path):
  493. for base, dirs, files in os.walk(path):
  494. for filename in files:
  495. self.outputs.append(os.path.join(base, filename))
  496. else:
  497. self.outputs.append(path)
  498. def not_editable(self, spec):
  499. if self.editable:
  500. raise DistutilsArgError(
  501. "Invalid argument %r: you can't use filenames or URLs "
  502. "with --editable (except via the --find-links option)."
  503. % (spec,)
  504. )
  505. def check_editable(self, spec):
  506. if not self.editable:
  507. return
  508. if os.path.exists(os.path.join(self.build_directory, spec.key)):
  509. raise DistutilsArgError(
  510. "%r already exists in %s; can't do a checkout there" %
  511. (spec.key, self.build_directory)
  512. )
  513. def easy_install(self, spec, deps=False):
  514. tmpdir = tempfile.mkdtemp(prefix="easy_install-")
  515. download = None
  516. if not self.editable:
  517. self.install_site_py()
  518. try:
  519. if not isinstance(spec, Requirement):
  520. if URL_SCHEME(spec):
  521. # It's a url, download it to tmpdir and process
  522. self.not_editable(spec)
  523. download = self.package_index.download(spec, tmpdir)
  524. return self.install_item(None, download, tmpdir, deps,
  525. True)
  526. elif os.path.exists(spec):
  527. # Existing file or directory, just process it directly
  528. self.not_editable(spec)
  529. return self.install_item(None, spec, tmpdir, deps, True)
  530. else:
  531. spec = parse_requirement_arg(spec)
  532. self.check_editable(spec)
  533. dist = self.package_index.fetch_distribution(
  534. spec, tmpdir, self.upgrade, self.editable,
  535. not self.always_copy, self.local_index
  536. )
  537. if dist is None:
  538. msg = "Could not find suitable distribution for %r" % spec
  539. if self.always_copy:
  540. msg += " (--always-copy skips system and development eggs)"
  541. raise DistutilsError(msg)
  542. elif dist.precedence == DEVELOP_DIST:
  543. # .egg-info dists don't need installing, just process deps
  544. self.process_distribution(spec, dist, deps, "Using")
  545. return dist
  546. else:
  547. return self.install_item(spec, dist.location, tmpdir, deps)
  548. finally:
  549. if os.path.exists(tmpdir):
  550. rmtree(tmpdir)
  551. def install_item(self, spec, download, tmpdir, deps, install_needed=False):
  552. # Installation is also needed if file in tmpdir or is not an egg
  553. install_needed = install_needed or self.always_copy
  554. install_needed = install_needed or os.path.dirname(download) == tmpdir
  555. install_needed = install_needed or not download.endswith('.egg')
  556. install_needed = install_needed or (
  557. self.always_copy_from is not None and
  558. os.path.dirname(normalize_path(download)) ==
  559. normalize_path(self.always_copy_from)
  560. )
  561. if spec and not install_needed:
  562. # at this point, we know it's a local .egg, we just don't know if
  563. # it's already installed.
  564. for dist in self.local_index[spec.project_name]:
  565. if dist.location == download:
  566. break
  567. else:
  568. install_needed = True # it's not in the local index
  569. log.info("Processing %s", os.path.basename(download))
  570. if install_needed:
  571. dists = self.install_eggs(spec, download, tmpdir)
  572. for dist in dists:
  573. self.process_distribution(spec, dist, deps)
  574. else:
  575. dists = [self.egg_distribution(download)]
  576. self.process_distribution(spec, dists[0], deps, "Using")
  577. if spec is not None:
  578. for dist in dists:
  579. if dist in spec:
  580. return dist
  581. def select_scheme(self, name):
  582. """Sets the install directories by applying the install schemes."""
  583. # it's the caller's problem if they supply a bad name!
  584. scheme = INSTALL_SCHEMES[name]
  585. for key in SCHEME_KEYS:
  586. attrname = 'install_' + key
  587. if getattr(self, attrname) is None:
  588. setattr(self, attrname, scheme[key])
  589. def process_distribution(self, requirement, dist, deps=True, *info):
  590. self.update_pth(dist)
  591. self.package_index.add(dist)
  592. if dist in self.local_index[dist.key]:
  593. self.local_index.remove(dist)
  594. self.local_index.add(dist)
  595. self.install_egg_scripts(dist)
  596. self.installed_projects[dist.key] = dist
  597. log.info(self.installation_report(requirement, dist, *info))
  598. if (dist.has_metadata('dependency_links.txt') and
  599. not self.no_find_links):
  600. self.package_index.add_find_links(
  601. dist.get_metadata_lines('dependency_links.txt')
  602. )
  603. if not deps and not self.always_copy:
  604. return
  605. elif requirement is not None and dist.key != requirement.key:
  606. log.warn("Skipping dependencies for %s", dist)
  607. return # XXX this is not the distribution we were looking for
  608. elif requirement is None or dist not in requirement:
  609. # if we wound up with a different version, resolve what we've got
  610. distreq = dist.as_requirement()
  611. requirement = requirement or distreq
  612. requirement = Requirement(
  613. distreq.project_name, distreq.specs, requirement.extras
  614. )
  615. log.info("Processing dependencies for %s", requirement)
  616. try:
  617. distros = WorkingSet([]).resolve(
  618. [requirement], self.local_index, self.easy_install
  619. )
  620. except DistributionNotFound as e:
  621. raise DistutilsError(str(e))
  622. except VersionConflict as e:
  623. raise DistutilsError(e.report())
  624. if self.always_copy or self.always_copy_from:
  625. # Force all the relevant distros to be copied or activated
  626. for dist in distros:
  627. if dist.key not in self.installed_projects:
  628. self.easy_install(dist.as_requirement())
  629. log.info("Finished processing dependencies for %s", requirement)
  630. def should_unzip(self, dist):
  631. if self.zip_ok is not None:
  632. return not self.zip_ok
  633. if dist.has_metadata('not-zip-safe'):
  634. return True
  635. if not dist.has_metadata('zip-safe'):
  636. return True
  637. return False
  638. def maybe_move(self, spec, dist_filename, setup_base):
  639. dst = os.path.join(self.build_directory, spec.key)
  640. if os.path.exists(dst):
  641. msg = ("%r already exists in %s; build directory %s will not be "
  642. "kept")
  643. log.warn(msg, spec.key, self.build_directory, setup_base)
  644. return setup_base
  645. if os.path.isdir(dist_filename):
  646. setup_base = dist_filename
  647. else:
  648. if os.path.dirname(dist_filename) == setup_base:
  649. os.unlink(dist_filename) # get it out of the tmp dir
  650. contents = os.listdir(setup_base)
  651. if len(contents) == 1:
  652. dist_filename = os.path.join(setup_base, contents[0])
  653. if os.path.isdir(dist_filename):
  654. # if the only thing there is a directory, move it instead
  655. setup_base = dist_filename
  656. ensure_directory(dst)
  657. shutil.move(setup_base, dst)
  658. return dst
  659. def install_wrapper_scripts(self, dist):
  660. if not self.exclude_scripts:
  661. for args in ScriptWriter.best().get_args(dist):
  662. self.write_script(*args)
  663. def install_script(self, dist, script_name, script_text, dev_path=None):
  664. """Generate a legacy script wrapper and install it"""
  665. spec = str(dist.as_requirement())
  666. is_script = is_python_script(script_text, script_name)
  667. if is_script:
  668. script_text = (ScriptWriter.get_header(script_text) +
  669. self._load_template(dev_path) % locals())
  670. self.write_script(script_name, _to_ascii(script_text), 'b')
  671. @staticmethod
  672. def _load_template(dev_path):
  673. """
  674. There are a couple of template scripts in the package. This
  675. function loads one of them and prepares it for use.
  676. """
  677. # See https://bitbucket.org/pypa/setuptools/issue/134 for info
  678. # on script file naming and downstream issues with SVR4
  679. name = 'script.tmpl'
  680. if dev_path:
  681. name = name.replace('.tmpl', ' (dev).tmpl')
  682. raw_bytes = resource_string('setuptools', name)
  683. return raw_bytes.decode('utf-8')
  684. def write_script(self, script_name, contents, mode="t", blockers=()):
  685. """Write an executable file to the scripts directory"""
  686. self.delete_blockers( # clean up old .py/.pyw w/o a script
  687. [os.path.join(self.script_dir, x) for x in blockers]
  688. )
  689. log.info("Installing %s script to %s", script_name, self.script_dir)
  690. target = os.path.join(self.script_dir, script_name)
  691. self.add_output(target)
  692. mask = current_umask()
  693. if not self.dry_run:
  694. ensure_directory(target)
  695. if os.path.exists(target):
  696. os.unlink(target)
  697. f = open(target, "w" + mode)
  698. f.write(contents)
  699. f.close()
  700. chmod(target, 0o777 - mask)
  701. def install_eggs(self, spec, dist_filename, tmpdir):
  702. # .egg dirs or files are already built, so just return them
  703. if dist_filename.lower().endswith('.egg'):
  704. return [self.install_egg(dist_filename, tmpdir)]
  705. elif dist_filename.lower().endswith('.exe'):
  706. return [self.install_exe(dist_filename, tmpdir)]
  707. # Anything else, try to extract and build
  708. setup_base = tmpdir
  709. if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
  710. unpack_archive(dist_filename, tmpdir, self.unpack_progress)
  711. elif os.path.isdir(dist_filename):
  712. setup_base = os.path.abspath(dist_filename)
  713. if (setup_base.startswith(tmpdir) # something we downloaded
  714. and self.build_directory and spec is not None):
  715. setup_base = self.maybe_move(spec, dist_filename, setup_base)
  716. # Find the setup.py file
  717. setup_script = os.path.join(setup_base, 'setup.py')
  718. if not os.path.exists(setup_script):
  719. setups = glob(os.path.join(setup_base, '*', 'setup.py'))
  720. if not setups:
  721. raise DistutilsError(
  722. "Couldn't find a setup script in %s" %
  723. os.path.abspath(dist_filename)
  724. )
  725. if len(setups) > 1:
  726. raise DistutilsError(
  727. "Multiple setup scripts in %s" %
  728. os.path.abspath(dist_filename)
  729. )
  730. setup_script = setups[0]
  731. # Now run it, and return the result
  732. if self.editable:
  733. log.info(self.report_editable(spec, setup_script))
  734. return []
  735. else:
  736. return self.build_and_install(setup_script, setup_base)
  737. def egg_distribution(self, egg_path):
  738. if os.path.isdir(egg_path):
  739. metadata = PathMetadata(egg_path, os.path.join(egg_path,
  740. 'EGG-INFO'))
  741. else:
  742. metadata = EggMetadata(zipimport.zipimporter(egg_path))
  743. return Distribution.from_filename(egg_path, metadata=metadata)
  744. def install_egg(self, egg_path, tmpdir):
  745. destination = os.path.join(self.install_dir,
  746. os.path.basename(egg_path))
  747. destination = os.path.abspath(destination)
  748. if not self.dry_run:
  749. ensure_directory(destination)
  750. dist = self.egg_distribution(egg_path)
  751. if not samefile(egg_path, destination):
  752. if os.path.isdir(destination) and not os.path.islink(destination):
  753. dir_util.remove_tree(destination, dry_run=self.dry_run)
  754. elif os.path.exists(destination):
  755. self.execute(os.unlink, (destination,), "Removing " +
  756. destination)
  757. try:
  758. new_dist_is_zipped = False
  759. if os.path.isdir(egg_path):
  760. if egg_path.startswith(tmpdir):
  761. f, m = shutil.move, "Moving"
  762. else:
  763. f, m = shutil.copytree, "Copying"
  764. elif self.should_unzip(dist):
  765. self.mkpath(destination)
  766. f, m = self.unpack_and_compile, "Extracting"
  767. else:
  768. new_dist_is_zipped = True
  769. if egg_path.startswith(tmpdir):
  770. f, m = shutil.move, "Moving"
  771. else:
  772. f, m = shutil.copy2, "Copying"
  773. self.execute(f, (egg_path, destination),
  774. (m + " %s to %s") %
  775. (os.path.basename(egg_path),
  776. os.path.dirname(destination)))
  777. update_dist_caches(destination,
  778. fix_zipimporter_caches=new_dist_is_zipped)
  779. except:
  780. update_dist_caches(destination, fix_zipimporter_caches=False)
  781. raise
  782. self.add_output(destination)
  783. return self.egg_distribution(destination)
  784. def install_exe(self, dist_filename, tmpdir):
  785. # See if it's valid, get data
  786. cfg = extract_wininst_cfg(dist_filename)
  787. if cfg is None:
  788. raise DistutilsError(
  789. "%s is not a valid distutils Windows .exe" % dist_filename
  790. )
  791. # Create a dummy distribution object until we build the real distro
  792. dist = Distribution(
  793. None,
  794. project_name=cfg.get('metadata', 'name'),
  795. version=cfg.get('metadata', 'version'), platform=get_platform(),
  796. )
  797. # Convert the .exe to an unpacked egg
  798. egg_path = dist.location = os.path.join(tmpdir, dist.egg_name() +
  799. '.egg')
  800. egg_tmp = egg_path + '.tmp'
  801. _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
  802. pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
  803. ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
  804. dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
  805. self.exe_to_egg(dist_filename, egg_tmp)
  806. # Write EGG-INFO/PKG-INFO
  807. if not os.path.exists(pkg_inf):
  808. f = open(pkg_inf, 'w')
  809. f.write('Metadata-Version: 1.0\n')
  810. for k, v in cfg.items('metadata'):
  811. if k != 'target_version':
  812. f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
  813. f.close()
  814. script_dir = os.path.join(_egg_info, 'scripts')
  815. # delete entry-point scripts to avoid duping
  816. self.delete_blockers(
  817. [os.path.join(script_dir, args[0]) for args in
  818. ScriptWriter.get_args(dist)]
  819. )
  820. # Build .egg file from tmpdir
  821. bdist_egg.make_zipfile(
  822. egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run
  823. )
  824. # install the .egg
  825. return self.install_egg(egg_path, tmpdir)
  826. def exe_to_egg(self, dist_filename, egg_tmp):
  827. """Extract a bdist_wininst to the directories an egg would use"""
  828. # Check for .pth file and set up prefix translations
  829. prefixes = get_exe_prefixes(dist_filename)
  830. to_compile = []
  831. native_libs = []
  832. top_level = {}
  833. def process(src, dst):
  834. s = src.lower()
  835. for old, new in prefixes:
  836. if s.startswith(old):
  837. src = new + src[len(old):]
  838. parts = src.split('/')
  839. dst = os.path.join(egg_tmp, *parts)
  840. dl = dst.lower()
  841. if dl.endswith('.pyd') or dl.endswith('.dll'):
  842. parts[-1] = bdist_egg.strip_module(parts[-1])
  843. top_level[os.path.splitext(parts[0])[0]] = 1
  844. native_libs.append(src)
  845. elif dl.endswith('.py') and old != 'SCRIPTS/':
  846. top_level[os.path.splitext(parts[0])[0]] = 1
  847. to_compile.append(dst)
  848. return dst
  849. if not src.endswith('.pth'):
  850. log.warn("WARNING: can't process %s", src)
  851. return None
  852. # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
  853. unpack_archive(dist_filename, egg_tmp, process)
  854. stubs = []
  855. for res in native_libs:
  856. if res.lower().endswith('.pyd'): # create stubs for .pyd's
  857. parts = res.split('/')
  858. resource = parts[-1]
  859. parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
  860. pyfile = os.path.join(egg_tmp, *parts)
  861. to_compile.append(pyfile)
  862. stubs.append(pyfile)
  863. bdist_egg.write_stub(resource, pyfile)
  864. self.byte_compile(to_compile) # compile .py's
  865. bdist_egg.write_safety_flag(
  866. os.path.join(egg_tmp, 'EGG-INFO'),
  867. bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
  868. for name in 'top_level', 'native_libs':
  869. if locals()[name]:
  870. txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
  871. if not os.path.exists(txt):
  872. f = open(txt, 'w')
  873. f.write('\n'.join(locals()[name]) + '\n')
  874. f.close()
  875. __mv_warning = textwrap.dedent("""
  876. Because this distribution was installed --multi-version, before you can
  877. import modules from this package in an application, you will need to
  878. 'import pkg_resources' and then use a 'require()' call similar to one of
  879. these examples, in order to select the desired version:
  880. pkg_resources.require("%(name)s") # latest installed version
  881. pkg_resources.require("%(name)s==%(version)s") # this exact version
  882. pkg_resources.require("%(name)s>=%(version)s") # this version or higher
  883. """).lstrip()
  884. __id_warning = textwrap.dedent("""
  885. Note also that the installation directory must be on sys.path at runtime for
  886. this to work. (e.g. by being the application's script directory, by being on
  887. PYTHONPATH, or by being added to sys.path by your code.)
  888. """)
  889. def installation_report(self, req, dist, what="Installed"):
  890. """Helpful installation message for display to package users"""
  891. msg = "\n%(what)s %(eggloc)s%(extras)s"
  892. if self.multi_version and not self.no_report:
  893. msg += '\n' + self.__mv_warning
  894. if self.install_dir not in map(normalize_path, sys.path):
  895. msg += '\n' + self.__id_warning
  896. eggloc = dist.location
  897. name = dist.project_name
  898. version = dist.version
  899. extras = '' # TODO: self.report_extras(req, dist)
  900. return msg % locals()
  901. __editable_msg = textwrap.dedent("""
  902. Extracted editable version of %(spec)s to %(dirname)s
  903. If it uses setuptools in its setup script, you can activate it in
  904. "development" mode by going to that directory and running::
  905. %(python)s setup.py develop
  906. See the setuptools documentation for the "develop" command for more info.
  907. """).lstrip()
  908. def report_editable(self, spec, setup_script):
  909. dirname = os.path.dirname(setup_script)
  910. python = sys.executable
  911. return '\n' + self.__editable_msg % locals()
  912. def run_setup(self, setup_script, setup_base, args):
  913. sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
  914. sys.modules.setdefault('distutils.command.egg_info', egg_info)
  915. args = list(args)
  916. if self.verbose > 2:
  917. v = 'v' * (self.verbose - 1)
  918. args.insert(0, '-' + v)
  919. elif self.verbose < 2:
  920. args.insert(0, '-q')
  921. if self.dry_run:
  922. args.insert(0, '-n')
  923. log.info(
  924. "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
  925. )
  926. try:
  927. run_setup(setup_script, args)
  928. except SystemExit as v:
  929. raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  930. def build_and_install(self, setup_script, setup_base):
  931. args = ['bdist_egg', '--dist-dir']
  932. dist_dir = tempfile.mkdtemp(
  933. prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
  934. )
  935. try:
  936. self._set_fetcher_options(os.path.dirname(setup_script))
  937. args.append(dist_dir)
  938. self.run_setup(setup_script, setup_base, args)
  939. all_eggs = Environment([dist_dir])
  940. eggs = []
  941. for key in all_eggs:
  942. for dist in all_eggs[key]:
  943. eggs.append(self.install_egg(dist.location, setup_base))
  944. if not eggs and not self.dry_run:
  945. log.warn("No eggs found in %s (setup script problem?)",
  946. dist_dir)
  947. return eggs
  948. finally:
  949. rmtree(dist_dir)
  950. log.set_verbosity(self.verbose) # restore our log verbosity
  951. def _set_fetcher_options(self, base):
  952. """
  953. When easy_install is about to run bdist_egg on a source dist, that
  954. source dist might have 'setup_requires' directives, requiring
  955. additional fetching. Ensure the fetcher options given to easy_install
  956. are available to that command as well.
  957. """
  958. # find the fetch options from easy_install and write them out
  959. # to the setup.cfg file.
  960. ei_opts = self.distribution.get_option_dict('easy_install').copy()
  961. fetch_directives = (
  962. 'find_links', 'site_dirs', 'index_url', 'optimize',
  963. 'site_dirs', 'allow_hosts',
  964. )
  965. fetch_options = {}
  966. for key, val in ei_opts.items():
  967. if key not in fetch_directives:
  968. continue
  969. fetch_options[key.replace('_', '-')] = val[1]
  970. # create a settings dictionary suitable for `edit_config`
  971. settings = dict(easy_install=fetch_options)
  972. cfg_filename = os.path.join(base, 'setup.cfg')
  973. setopt.edit_config(cfg_filename, settings)
  974. def update_pth(self, dist):
  975. if self.pth_file is None:
  976. return
  977. for d in self.pth_file[dist.key]: # drop old entries
  978. if self.multi_version or d.location != dist.location:
  979. log.info("Removing %s from easy-install.pth file", d)
  980. self.pth_file.remove(d)
  981. if d.location in self.shadow_path:
  982. self.shadow_path.remove(d.location)
  983. if not self.multi_version:
  984. if dist.location in self.pth_file.paths:
  985. log.info(
  986. "%s is already the active version in easy-install.pth",
  987. dist
  988. )
  989. else:
  990. log.info("Adding %s to easy-install.pth file", dist)
  991. self.pth_file.add(dist) # add new entry
  992. if dist.location not in self.shadow_path:
  993. self.shadow_path.append(dist.location)
  994. if not self.dry_run:
  995. self.pth_file.save()
  996. if dist.key == 'setuptools':
  997. # Ensure that setuptools itself never becomes unavailable!
  998. # XXX should this check for latest version?
  999. filename = os.path.join(self.install_dir, 'setuptools.pth')
  1000. if os.path.islink(filename):
  1001. os.unlink(filename)
  1002. f = open(filename, 'wt')
  1003. f.write(self.pth_file.make_relative(dist.location) + '\n')
  1004. f.close()
  1005. def unpack_progress(self, src, dst):
  1006. # Progress filter for unpacking
  1007. log.debug("Unpacking %s to %s", src, dst)
  1008. return dst # only unpack-and-compile skips files for dry run
  1009. def unpack_and_compile(self, egg_path, destination):
  1010. to_compile = []
  1011. to_chmod = []
  1012. def pf(src, dst):
  1013. if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
  1014. to_compile.append(dst)
  1015. elif dst.endswith('.dll') or dst.endswith('.so'):
  1016. to_chmod.append(dst)
  1017. self.unpack_progress(src, dst)
  1018. return not self.dry_run and dst or None
  1019. unpack_archive(egg_path, destination, pf)
  1020. self.byte_compile(to_compile)
  1021. if not self.dry_run:
  1022. for f in to_chmod:
  1023. mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
  1024. chmod(f, mode)
  1025. def byte_compile(self, to_compile):
  1026. if sys.dont_write_bytecode:
  1027. self.warn('byte-compiling is disabled, skipping.')
  1028. return
  1029. from distutils.util import byte_compile
  1030. try:
  1031. # try to make the byte compile messages quieter
  1032. log.set_verbosity(self.verbose - 1)
  1033. byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
  1034. if self.optimize:
  1035. byte_compile(
  1036. to_compile, optimize=self.optimize, force=1,
  1037. dry_run=self.dry_run
  1038. )
  1039. finally:
  1040. log.set_verbosity(self.verbose) # restore original verbosity
  1041. __no_default_msg = textwrap.dedent("""
  1042. bad install directory or PYTHONPATH
  1043. You are attempting to install a package to a directory that is not
  1044. on PYTHONPATH and which Python does not read ".pth" files from. The
  1045. installation directory you specified (via --install-dir, --prefix, or
  1046. the distutils default setting) was:
  1047. %s
  1048. and your PYTHONPATH environment variable currently contains:
  1049. %r
  1050. Here are some of your options for correcting the problem:
  1051. * You can choose a different installation directory, i.e., one that is
  1052. on PYTHONPATH or supports .pth files
  1053. * You can add the installation directory to the PYTHONPATH environment
  1054. variable. (It must then also be on PYTHONPATH whenever you run
  1055. Python and want to use the package(s) you are installing.)
  1056. * You can set up the installation directory to support ".pth" files by
  1057. using one of the approaches described here:
  1058. https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations
  1059. Please make the appropriate changes for your system and try again.""").lstrip()
  1060. def no_default_version_msg(self):
  1061. template = self.__no_default_msg
  1062. return template % (self.install_dir, os.environ.get('PYTHONPATH', ''))
  1063. def install_site_py(self):
  1064. """Make sure there's a site.py in the target dir, if needed"""
  1065. if self.sitepy_installed:
  1066. return # already did it, or don't need to
  1067. sitepy = os.path.join(self.install_dir, "site.py")
  1068. source = resource_string("setuptools", "site-patch.py")
  1069. current = ""
  1070. if os.path.exists(sitepy):
  1071. log.debug("Checking existing site.py in %s", self.install_dir)
  1072. f = open(sitepy, 'rb')
  1073. current = f.read()
  1074. # we want str, not bytes
  1075. if PY3:
  1076. current = current.decode()
  1077. f.close()
  1078. if not current.startswith('def __boot():'):
  1079. raise DistutilsError(
  1080. "%s is not a setuptools-generated site.py; please"
  1081. " remove it." % sitepy
  1082. )
  1083. if current != source:
  1084. log.info("Creating %s", sitepy)
  1085. if not self.dry_run:
  1086. ensure_directory(sitepy)
  1087. f = open(sitepy, 'wb')
  1088. f.write(source)
  1089. f.close()
  1090. self.byte_compile([sitepy])
  1091. self.sitepy_installed = True
  1092. def create_home_path(self):
  1093. """Create directories under ~."""
  1094. if not self.user:
  1095. return
  1096. home = convert_path(os.path.expanduser("~"))
  1097. for name, path in iteritems(self.config_vars):
  1098. if path.startswith(home) and not os.path.isdir(path):
  1099. self.debug_print("os.makedirs('%s', 0o700)" % path)
  1100. os.makedirs(path, 0o700)
  1101. INSTALL_SCHEMES = dict(
  1102. posix=dict(
  1103. install_dir='$base/lib/python$py_version_short/site-packages',
  1104. script_dir='$base/bin',
  1105. ),
  1106. )
  1107. DEFAULT_SCHEME = dict(
  1108. install_dir='$base/Lib/site-packages',
  1109. script_dir='$base/Scripts',
  1110. )
  1111. def _expand(self, *attrs):
  1112. config_vars = self.get_finalized_command('install').config_vars
  1113. if self.prefix:
  1114. # Set default install_dir/scripts from --prefix
  1115. config_vars = config_vars.copy()
  1116. config_vars['base'] = self.prefix
  1117. scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
  1118. for attr, val in scheme.items():
  1119. if getattr(self, attr, None) is None:
  1120. setattr(self, attr, val)
  1121. from distutils.util import subst_vars
  1122. for attr in attrs:
  1123. val = getattr(self, attr)
  1124. if val is not None:
  1125. val = subst_vars(val, config_vars)
  1126. if os.name == 'posix':
  1127. val = os.path.expanduser(val)
  1128. setattr(self, attr, val)
  1129. def get_site_dirs():
  1130. # return a list of 'site' dirs
  1131. sitedirs = [_f for _f in os.environ.get('PYTHONPATH',
  1132. '').split(os.pathsep) if _f]
  1133. prefixes = [sys.prefix]
  1134. if sys.exec_prefix != sys.prefix:
  1135. prefixes.append(sys.exec_prefix)
  1136. for prefix in prefixes:
  1137. if prefix:
  1138. if sys.platform in ('os2emx', 'riscos'):
  1139. sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  1140. elif os.sep == '/':
  1141. sitedirs.extend([os.path.join(prefix,
  1142. "lib",
  1143. "python" + sys.version[:3],
  1144. "site-packages"),
  1145. os.path.join(prefix, "lib", "site-python")])
  1146. else:
  1147. sitedirs.extend(
  1148. [prefix, os.path.join(prefix, "lib", "site-packages")]
  1149. )
  1150. if sys.platform == 'darwin':
  1151. # for framework builds *only* we add the standard Apple
  1152. # locations. Currently only per-user, but /Library and
  1153. # /Network/Library could be added too
  1154. if 'Python.framework' in prefix:
  1155. home = os.environ.get('HOME')
  1156. if home:
  1157. sitedirs.append(
  1158. os.path.join(home,
  1159. 'Library',
  1160. 'Python',
  1161. sys.version[:3],
  1162. 'site-packages'))
  1163. lib_paths = get_path('purelib'), get_path('platlib')
  1164. for site_lib in lib_paths:
  1165. if site_lib not in sitedirs:
  1166. sitedirs.append(site_lib)
  1167. if site.ENABLE_USER_SITE:
  1168. sitedirs.append(site.USER_SITE)
  1169. sitedirs = list(map(normalize_path, sitedirs))
  1170. return sitedirs
  1171. def expand_paths(inputs):
  1172. """Yield sys.path directories that might contain "old-style" packages"""
  1173. seen = {}
  1174. for dirname in inputs:
  1175. dirname = normalize_path(dirname)
  1176. if dirname in seen:
  1177. continue
  1178. seen[dirname] = 1
  1179. if not os.path.isdir(dirname):
  1180. continue
  1181. files = os.listdir(dirname)
  1182. yield dirname, files
  1183. for name in files:
  1184. if not name.endswith('.pth'):
  1185. # We only care about the .pth files
  1186. continue
  1187. if name in ('easy-install.pth', 'setuptools.pth'):
  1188. # Ignore .pth files that we control
  1189. continue
  1190. # Read the .pth file
  1191. f = open(os.path.join(dirname, name))
  1192. lines = list(yield_lines(f))
  1193. f.close()
  1194. # Yield existing non-dupe, non-import directory lines from it
  1195. for line in lines:
  1196. if not line.startswith("import"):
  1197. line = normalize_path(line.rstrip())
  1198. if line not in seen:
  1199. seen[line] = 1
  1200. if not os.path.isdir(line):
  1201. continue
  1202. yield line, os.listdir(line)
  1203. def extract_wininst_cfg(dist_filename):
  1204. """Extract configuration data from a bdist_wininst .exe
  1205. Returns a ConfigParser.RawConfigParser, or None
  1206. """
  1207. f = open(dist_filename, 'rb')
  1208. try:
  1209. endrec = zipfile._EndRecData(f)
  1210. if endrec is None:
  1211. return None
  1212. prepended = (endrec[9] - endrec[5]) - endrec[6]
  1213. if prepended < 12: # no wininst data here
  1214. return None
  1215. f.seek(prepended - 12)
  1216. from setuptools.compat import StringIO, ConfigParser
  1217. import struct
  1218. tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
  1219. if tag not in (0x1234567A, 0x1234567B):
  1220. return None # not a valid tag
  1221. f.seek(prepended - (12 + cfglen))
  1222. cfg = ConfigParser.RawConfigParser(
  1223. {'version': '', 'target_version': ''})
  1224. try:
  1225. part = f.read(cfglen)
  1226. # Read up to the first null byte.
  1227. config = part.split(b'\0', 1)[0]
  1228. # Now the config is in bytes, but for RawConfigParser, it should
  1229. # be text, so decode it.
  1230. config = config.decode(sys.getfilesystemencoding())
  1231. cfg.readfp(StringIO(config))
  1232. except ConfigParser.Error:
  1233. return None
  1234. if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
  1235. return None
  1236. return cfg
  1237. finally:
  1238. f.close()
  1239. def get_exe_prefixes(exe_filename):
  1240. """Get exe->egg path translations for a given .exe file"""
  1241. prefixes = [
  1242. ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
  1243. ('PLATLIB/', ''),
  1244. ('SCRIPTS/', 'EGG-INFO/scripts/'),
  1245. ('DATA/lib/site-packages', ''),
  1246. ]
  1247. z = zipfile.ZipFile(exe_filename)
  1248. try:
  1249. for info in z.infolist():
  1250. name = info.filename
  1251. parts = name.split('/')
  1252. if len(parts) == 3 and parts[2] == 'PKG-INFO':
  1253. if parts[1].endswith('.egg-info'):
  1254. prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
  1255. break
  1256. if len(parts) != 2 or not name.endswith('.pth'):
  1257. continue
  1258. if name.endswith('-nspkg.pth'):
  1259. continue
  1260. if parts[0].upper() in ('PURELIB', 'PLATLIB'):
  1261. contents = z.read(name)
  1262. if PY3:
  1263. contents = contents.decode()
  1264. for pth in yield_lines(contents):
  1265. pth = pth.strip().replace('\\', '/')
  1266. if not pth.startswith('import'):
  1267. prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
  1268. finally:
  1269. z.close()
  1270. prefixes = [(x.lower(), y) for x, y in prefixes]
  1271. prefixes.sort()
  1272. prefixes.reverse()
  1273. return prefixes
  1274. def parse_requirement_arg(spec):
  1275. try:
  1276. return Requirement.parse(spec)
  1277. except ValueError:
  1278. raise DistutilsError(
  1279. "Not a URL, existing file, or requirement spec: %r" % (spec,)
  1280. )
  1281. class PthDistributions(Environment):
  1282. """A .pth file with Distribution paths in it"""
  1283. dirty = False
  1284. def __init__(self, filename, sitedirs=()):
  1285. self.filename = filename
  1286. self.sitedirs = list(map(normalize_path, sitedirs))
  1287. self.basedir = normalize_path(os.path.dirname(self.filename))
  1288. self._load()
  1289. Environment.__init__(self, [], None, None)
  1290. for path in yield_lines(self.paths):
  1291. list(map(self.add, find_distributions(path, True)))
  1292. def _load(self):
  1293. self.paths = []
  1294. saw_import = False
  1295. seen = dict.fromkeys(self.sitedirs)
  1296. if os.path.isfile(self.filename):
  1297. f = open(self.filename, 'rt')
  1298. for line in f:
  1299. if line.startswith('import'):
  1300. saw_import = True
  1301. continue
  1302. path = line.rstrip()
  1303. self.paths.append(path)
  1304. if not path.strip() or path.strip().startswith('#'):
  1305. continue
  1306. # skip non-existent paths, in case somebody deleted a package
  1307. # manually, and duplicate paths as well
  1308. path = self.paths[-1] = normalize_path(
  1309. os.path.join(self.basedir, path)
  1310. )
  1311. if not os.path.exists(path) or path in seen:
  1312. self.paths.pop() # skip it
  1313. self.dirty = True # we cleaned up, so we're dirty now :)
  1314. continue
  1315. seen[path] = 1
  1316. f.close()
  1317. if self.paths and not saw_import:
  1318. self.dirty = True # ensure anything we touch has import wrappers
  1319. while self.paths and not self.paths[-1].strip():
  1320. self.paths.pop()
  1321. def save(self):
  1322. """Write changed .pth file back to disk"""
  1323. if not self.dirty:
  1324. return
  1325. data = '\n'.join(map(self.make_relative, self.paths))
  1326. if data:
  1327. log.debug("Saving %s", self.filename)
  1328. data = (
  1329. "import sys; sys.__plen = len(sys.path)\n"
  1330. "%s\n"
  1331. "import sys; new=sys.path[sys.__plen:];"
  1332. " del sys.path[sys.__plen:];"
  1333. " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;"
  1334. " sys.__egginsert = p+len(new)\n"
  1335. ) % data
  1336. if os.path.islink(self.filename):
  1337. os.unlink(self.filename)
  1338. f = open(self.filename, 'wt')
  1339. f.write(data)
  1340. f.close()
  1341. elif os.path.exists(self.filename):
  1342. log.debug("Deleting empty %s", self.filename)
  1343. os.unlink(self.filename)
  1344. self.dirty = False
  1345. def add(self, dist):
  1346. """Add `dist` to the distribution map"""
  1347. new_path = (
  1348. dist.location not in self.paths and (
  1349. dist.location not in self.sitedirs or
  1350. # account for '.' being in PYTHONPATH
  1351. dist.location == os.getcwd()
  1352. )
  1353. )
  1354. if new_path:
  1355. self.paths.append(dist.location)
  1356. self.dirty = True
  1357. Environment.add(self, dist)
  1358. def remove(self, dist):
  1359. """Remove `dist` from the distribution map"""
  1360. while dist.location in self.paths:
  1361. self.paths.remove(dist.location)
  1362. self.dirty = True
  1363. Environment.remove(self, dist)
  1364. def make_relative(self, path):
  1365. npath, last = os.path.split(normalize_path(path))
  1366. baselen = len(self.basedir)
  1367. parts = [last]
  1368. sep = os.altsep == '/' and '/' or os.sep
  1369. while len(npath) >= baselen:
  1370. if npath == self.basedir:
  1371. parts.append(os.curdir)
  1372. parts.reverse()
  1373. return sep.join(parts)
  1374. npath, last = os.path.split(npath)
  1375. parts.append(last)
  1376. else:
  1377. return path
  1378. def _first_line_re():
  1379. """
  1380. Return a regular expression based on first_line_re suitable for matching
  1381. strings.
  1382. """
  1383. if isinstance(first_line_re.pattern, str):
  1384. return first_line_re
  1385. # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
  1386. return re.compile(first_line_re.pattern.decode())
  1387. def auto_chmod(func, arg, exc):
  1388. if func is os.remove and os.name == 'nt':
  1389. chmod(arg, stat.S_IWRITE)
  1390. return func(arg)
  1391. et, ev, _ = sys.exc_info()
  1392. reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg))))
  1393. def update_dist_caches(dist_path, fix_zipimporter_caches):
  1394. """
  1395. Fix any globally cached `dist_path` related data
  1396. `dist_path` should be a path of a newly installed egg distribution (zipped
  1397. or unzipped).
  1398. sys.path_importer_cache contains finder objects that have been cached when
  1399. importing data from the original distribution. Any such finders need to be
  1400. cleared since the replacement distribution might be packaged differently,
  1401. e.g. a zipped egg distribution might get replaced with an unzipped egg
  1402. folder or vice versa. Having the old finders cached may then cause Python
  1403. to attempt loading modules from the replacement distribution using an
  1404. incorrect loader.
  1405. zipimport.zipimporter objects are Python loaders charged with importing
  1406. data packaged inside zip archives. If stale loaders referencing the
  1407. original distribution, are left behind, they can fail to load modules from
  1408. the replacement distribution. E.g. if an old zipimport.zipimporter instance
  1409. is used to load data from a new zipped egg archive, it may cause the
  1410. operation to attempt to locate the requested data in the wrong location -
  1411. one indicated by the original distribution's zip archive directory
  1412. information. Such an operation may then fail outright, e.g. report having
  1413. read a 'bad local file header', or even worse, it may fail silently &
  1414. return invalid data.
  1415. zipimport._zip_directory_cache contains cached zip archive directory
  1416. information for all existing zipimport.zipimporter instances and all such
  1417. instances connected to the same archive share the same cached directory
  1418. information.
  1419. If asked, and the underlying Python implementation allows it, we can fix
  1420. all existing zipimport.zipimporter instances instead of having to track
  1421. them down and remove them one by one, by updating their shared cached zip
  1422. archive directory information. This, of course, assumes that the
  1423. replacement distribution is packaged as a zipped egg.
  1424. If not asked to fix existing zipimport.zipimporter instances, we still do
  1425. our best to clear any remaining zipimport.zipimporter related cached data
  1426. that might somehow later get used when attempting to load data from the new
  1427. distribution and thus cause such load operations to fail. Note that when
  1428. tracking down such remaining stale data, we can not catch every conceivable
  1429. usage from here, and we clear only those that we know of and have found to
  1430. cause problems if left alive. Any remaining caches should be updated by
  1431. whomever is in charge of maintaining them, i.e. they should be ready to
  1432. handle us replacing their zip archives with new distributions at runtime.
  1433. """
  1434. # There are several other known sources of stale zipimport.zipimporter
  1435. # instances that we do not clear here, but might if ever given a reason to
  1436. # do so:
  1437. # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
  1438. # set') may contain distributions which may in turn contain their
  1439. # zipimport.zipimporter loaders.
  1440. # * Several zipimport.zipimporter loaders held by local variables further
  1441. # up the function call stack when running the setuptools installation.
  1442. # * Already loaded modules may have their __loader__ attribute set to the
  1443. # exact loader instance used when importing them. Python 3.4 docs state
  1444. # that this information is intended mostly for introspection and so is
  1445. # not expected to cause us problems.
  1446. normalized_path = normalize_path(dist_path)
  1447. _uncache(normalized_path, sys.path_importer_cache)
  1448. if fix_zipimporter_caches:
  1449. _replace_zip_directory_cache_data(normalized_path)
  1450. else:
  1451. # Here, even though we do not want to fix existing and now stale
  1452. # zipimporter cache information, we still want to remove it. Related to
  1453. # Python's zip archive directory information cache, we clear each of
  1454. # its stale entries in two phases:
  1455. # 1. Clear the entry so attempting to access zip archive information
  1456. # via any existing stale zipimport.zipimporter instances fails.
  1457. # 2. Remove the entry from the cache so any newly constructed
  1458. # zipimport.zipimporter instances do not end up using old stale
  1459. # zip archive directory information.
  1460. # This whole stale data removal step does not seem strictly necessary,
  1461. # but has been left in because it was done before we started replacing
  1462. # the zip archive directory information cache content if possible, and
  1463. # there are no relevant unit tests that we can depend on to tell us if
  1464. # this is really needed.
  1465. _remove_and_clear_zip_directory_cache_data(normalized_path)
  1466. def _collect_zipimporter_cache_entries(normalized_path, cache):
  1467. """
  1468. Return zipimporter cache entry keys related to a given normalized path.
  1469. Alternative path spellings (e.g. those using different character case or
  1470. those using alternative path separators) related to the same path are
  1471. included. Any sub-path entries are included as well, i.e. those
  1472. corresponding to zip archives embedded in other zip archives.
  1473. """
  1474. result = []
  1475. prefix_len = len(normalized_path)
  1476. for p in cache:
  1477. np = normalize_path(p)
  1478. if (np.startswith(normalized_path) and
  1479. np[prefix_len:prefix_len + 1] in (os.sep, '')):
  1480. result.append(p)
  1481. return result
  1482. def _update_zipimporter_cache(normalized_path, cache, updater=None):
  1483. """
  1484. Update zipimporter cache data for a given normalized path.
  1485. Any sub-path entries are processed as well, i.e. those corresponding to zip
  1486. archives embedded in other zip archives.
  1487. Given updater is a callable taking a cache entry key and the original entry
  1488. (after already removing the entry from the cache), and expected to update
  1489. the entry and possibly return a new one to be inserted in its place.
  1490. Returning None indicates that the entry should not be replaced with a new
  1491. one. If no updater is given, the cache entries are simply removed without
  1492. any additional processing, the same as if the updater simply returned None.
  1493. """
  1494. for p in _collect_zipimporter_cache_entries(normalized_path, cache):
  1495. # N.B. pypy's custom zipimport._zip_directory_cache implementation does
  1496. # not support the complete dict interface:
  1497. # * Does not support item assignment, thus not allowing this function
  1498. # to be used only for removing existing cache entries.
  1499. # * Does not support the dict.pop() method, forcing us to use the
  1500. # get/del patterns instead. For more detailed information see the
  1501. # following links:
  1502. # https://bitbucket.org/pypa/setuptools/issue/202/more-robust-zipimporter-cache-invalidation#comment-10495960
  1503. # https://bitbucket.org/pypy/pypy/src/dd07756a34a41f674c0cacfbc8ae1d4cc9ea2ae4/pypy/module/zipimport/interp_zipimport.py#cl-99
  1504. old_entry = cache[p]
  1505. del cache[p]
  1506. new_entry = updater and updater(p, old_entry)
  1507. if new_entry is not None:
  1508. cache[p] = new_entry
  1509. def _uncache(normalized_path, cache):
  1510. _update_zipimporter_cache(normalized_path, cache)
  1511. def _remove_and_clear_zip_directory_cache_data(normalized_path):
  1512. def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
  1513. old_entry.clear()
  1514. _update_zipimporter_cache(
  1515. normalized_path, zipimport._zip_directory_cache,
  1516. updater=clear_and_remove_cached_zip_archive_directory_data)
  1517. # PyPy Python implementation does not allow directly writing to the
  1518. # zipimport._zip_directory_cache and so prevents us from attempting to correct
  1519. # its content. The best we can do there is clear the problematic cache content
  1520. # and have PyPy repopulate it as needed. The downside is that if there are any
  1521. # stale zipimport.zipimporter instances laying around, attempting to use them
  1522. # will fail due to not having its zip archive directory information available
  1523. # instead of being automatically corrected to use the new correct zip archive
  1524. # directory information.
  1525. if '__pypy__' in sys.builtin_module_names:
  1526. _replace_zip_directory_cache_data = \
  1527. _remove_and_clear_zip_directory_cache_data
  1528. else:
  1529. def _replace_zip_directory_cache_data(normalized_path):
  1530. def replace_cached_zip_archive_directory_data(path, old_entry):
  1531. # N.B. In theory, we could load the zip directory information just
  1532. # once for all updated path spellings, and then copy it locally and
  1533. # update its contained path strings to contain the correct
  1534. # spelling, but that seems like a way too invasive move (this cache
  1535. # structure is not officially documented anywhere and could in
  1536. # theory change with new Python releases) for no significant
  1537. # benefit.
  1538. old_entry.clear()
  1539. zipimport.zipimporter(path)
  1540. old_entry.update(zipimport._zip_directory_cache[path])
  1541. return old_entry
  1542. _update_zipimporter_cache(
  1543. normalized_path, zipimport._zip_directory_cache,
  1544. updater=replace_cached_zip_archive_directory_data)
  1545. def is_python(text, filename='<string>'):
  1546. "Is this string a valid Python script?"
  1547. try:
  1548. compile(text, filename, 'exec')
  1549. except (SyntaxError, TypeError):
  1550. return False
  1551. else:
  1552. return True
  1553. def is_sh(executable):
  1554. """Determine if the specified executable is a .sh (contains a #! line)"""
  1555. try:
  1556. with io.open(executable, encoding='latin-1') as fp:
  1557. magic = fp.read(2)
  1558. except (OSError, IOError):
  1559. return executable
  1560. return magic == '#!'
  1561. def nt_quote_arg(arg):
  1562. """Quote a command line argument according to Windows parsing rules"""
  1563. return subprocess.list2cmdline([arg])
  1564. def is_python_script(script_text, filename):
  1565. """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
  1566. """
  1567. if filename.endswith('.py') or filename.endswith('.pyw'):
  1568. return True # extension says it's Python
  1569. if is_python(script_text, filename):
  1570. return True # it's syntactically valid Python
  1571. if script_text.startswith('#!'):
  1572. # It begins with a '#!' line, so check if 'python' is in it somewhere
  1573. return 'python' in script_text.splitlines()[0].lower()
  1574. return False # Not any Python I can recognize
  1575. try:
  1576. from os import chmod as _chmod
  1577. except ImportError:
  1578. # Jython compatibility
  1579. def _chmod(*args):
  1580. pass
  1581. def chmod(path, mode):
  1582. log.debug("changing mode of %s to %o", path, mode)
  1583. try:
  1584. _chmod(path, mode)
  1585. except os.error as e:
  1586. log.debug("chmod failed: %s", e)
  1587. def fix_jython_executable(executable, options):
  1588. warnings.warn("Use JythonCommandSpec", DeprecationWarning, stacklevel=2)
  1589. if not JythonCommandSpec.relevant():
  1590. return executable
  1591. cmd = CommandSpec.best().from_param(executable)
  1592. cmd.install_options(options)
  1593. return cmd.as_header().lstrip('#!').rstrip('\n')
  1594. class CommandSpec(list):
  1595. """
  1596. A command spec for a #! header, specified as a list of arguments akin to
  1597. those passed to Popen.
  1598. """
  1599. options = []
  1600. split_args = dict()
  1601. @classmethod
  1602. def best(cls):
  1603. """
  1604. Choose the best CommandSpec class based on environmental conditions.
  1605. """
  1606. return cls if not JythonCommandSpec.relevant() else JythonCommandSpec
  1607. @classmethod
  1608. def _sys_executable(cls):
  1609. _default = os.path.normpath(sys.executable)
  1610. return os.environ.get('__PYVENV_LAUNCHER__', _default)
  1611. @classmethod
  1612. def from_param(cls, param):
  1613. """
  1614. Construct a CommandSpec from a parameter to build_scripts, which may
  1615. be None.
  1616. """
  1617. if isinstance(param, cls):
  1618. return param
  1619. if isinstance(param, list):
  1620. return cls(param)
  1621. if param is None:
  1622. return cls.from_environment()
  1623. # otherwise, assume it's a string.
  1624. return cls.from_string(param)
  1625. @classmethod
  1626. def from_environment(cls):
  1627. return cls([cls._sys_executable()])
  1628. @classmethod
  1629. def from_string(cls, string):
  1630. """
  1631. Construct a command spec from a simple string representing a command
  1632. line parseable by shlex.split.
  1633. """
  1634. items = shlex.split(string, **cls.split_args)
  1635. return cls(items)
  1636. def install_options(self, script_text):
  1637. self.options = shlex.split(self._extract_options(script_text))
  1638. cmdline = subprocess.list2cmdline(self)
  1639. if not isascii(cmdline):
  1640. self.options[:0] = ['-x']
  1641. @staticmethod
  1642. def _extract_options(orig_script):
  1643. """
  1644. Extract any options from the first line of the script.
  1645. """
  1646. first = (orig_script + '\n').splitlines()[0]
  1647. match = _first_line_re().match(first)
  1648. options = match.group(1) or '' if match else ''
  1649. return options.strip()
  1650. def as_header(self):
  1651. return self._render(self + list(self.options))
  1652. @staticmethod
  1653. def _render(items):
  1654. cmdline = subprocess.list2cmdline(items)
  1655. return '#!' + cmdline + '\n'
  1656. # For pbr compat; will be removed in a future version.
  1657. sys_executable = CommandSpec._sys_executable()
  1658. class WindowsCommandSpec(CommandSpec):
  1659. split_args = dict(posix=False)
  1660. class JythonCommandSpec(CommandSpec):
  1661. @classmethod
  1662. def relevant(cls):
  1663. return (
  1664. sys.platform.startswith('java')
  1665. and
  1666. __import__('java').lang.System.getProperty('os.name') != 'Linux'
  1667. )
  1668. def as_header(self):
  1669. """
  1670. Workaround Jython's sys.executable being a .sh (an invalid
  1671. shebang line interpreter)
  1672. """
  1673. if not is_sh(self[0]):
  1674. return super(JythonCommandSpec, self).as_header()
  1675. if self.options:
  1676. # Can't apply the workaround, leave it broken
  1677. log.warn(
  1678. "WARNING: Unable to adapt shebang line for Jython,"
  1679. " the following script is NOT executable\n"
  1680. " see http://bugs.jython.org/issue1112 for"
  1681. " more information.")
  1682. return super(JythonCommandSpec, self).as_header()
  1683. items = ['/usr/bin/env'] + self + list(self.options)
  1684. return self._render(items)
  1685. class ScriptWriter(object):
  1686. """
  1687. Encapsulates behavior around writing entry point scripts for console and
  1688. gui apps.
  1689. """
  1690. template = textwrap.dedent("""
  1691. # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
  1692. __requires__ = %(spec)r
  1693. import sys
  1694. from pkg_resources import load_entry_point
  1695. if __name__ == '__main__':
  1696. sys.exit(
  1697. load_entry_point(%(spec)r, %(group)r, %(name)r)()
  1698. )
  1699. """).lstrip()
  1700. command_spec_class = CommandSpec
  1701. @classmethod
  1702. def get_script_args(cls, dist, executable=None, wininst=False):
  1703. # for backward compatibility
  1704. warnings.warn("Use get_args", DeprecationWarning)
  1705. writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
  1706. header = cls.get_script_header("", executable, wininst)
  1707. return writer.get_args(dist, header)
  1708. @classmethod
  1709. def get_script_header(cls, script_text, executable=None, wininst=False):
  1710. # for backward compatibility
  1711. warnings.warn("Use get_header", DeprecationWarning)
  1712. if wininst:
  1713. executable = "python.exe"
  1714. cmd = cls.command_spec_class.best().from_param(executable)
  1715. cmd.install_options(script_text)
  1716. return cmd.as_header()
  1717. @classmethod
  1718. def get_args(cls, dist, header=None):
  1719. """
  1720. Yield write_script() argument tuples for a distribution's
  1721. console_scripts and gui_scripts entry points.
  1722. """
  1723. if header is None:
  1724. header = cls.get_header()
  1725. spec = str(dist.as_requirement())
  1726. for type_ in 'console', 'gui':
  1727. group = type_ + '_scripts'
  1728. for name, ep in dist.get_entry_map(group).items():
  1729. cls._ensure_safe_name(name)
  1730. script_text = cls.template % locals()
  1731. args = cls._get_script_args(type_, name, header, script_text)
  1732. for res in args:
  1733. yield res
  1734. @staticmethod
  1735. def _ensure_safe_name(name):
  1736. """
  1737. Prevent paths in *_scripts entry point names.
  1738. """
  1739. has_path_sep = re.search(r'[\\/]', name)
  1740. if has_path_sep:
  1741. raise ValueError("Path separators not allowed in script names")
  1742. @classmethod
  1743. def get_writer(cls, force_windows):
  1744. # for backward compatibility
  1745. warnings.warn("Use best", DeprecationWarning)
  1746. return WindowsScriptWriter.best() if force_windows else cls.best()
  1747. @classmethod
  1748. def best(cls):
  1749. """
  1750. Select the best ScriptWriter for this environment.
  1751. """
  1752. return WindowsScriptWriter.best() if sys.platform == 'win32' else cls
  1753. @classmethod
  1754. def _get_script_args(cls, type_, name, header, script_text):
  1755. # Simply write the stub with no extension.
  1756. yield (name, header + script_text)
  1757. @classmethod
  1758. def get_header(cls, script_text="", executable=None):
  1759. """Create a #! line, getting options (if any) from script_text"""
  1760. cmd = cls.command_spec_class.best().from_param(executable)
  1761. cmd.install_options(script_text)
  1762. return cmd.as_header()
  1763. class WindowsScriptWriter(ScriptWriter):
  1764. command_spec_class = WindowsCommandSpec
  1765. @classmethod
  1766. def get_writer(cls):
  1767. # for backward compatibility
  1768. warnings.warn("Use best", DeprecationWarning)
  1769. return cls.best()
  1770. @classmethod
  1771. def best(cls):
  1772. """
  1773. Select the best ScriptWriter suitable for Windows
  1774. """
  1775. writer_lookup = dict(
  1776. executable=WindowsExecutableLauncherWriter,
  1777. natural=cls,
  1778. )
  1779. # for compatibility, use the executable launcher by default
  1780. launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
  1781. return writer_lookup[launcher]
  1782. @classmethod
  1783. def _get_script_args(cls, type_, name, header, script_text):
  1784. "For Windows, add a .py extension"
  1785. ext = dict(console='.pya', gui='.pyw')[type_]
  1786. if ext not in os.environ['PATHEXT'].lower().split(';'):
  1787. warnings.warn("%s not listed in PATHEXT; scripts will not be "
  1788. "recognized as executables." % ext, UserWarning)
  1789. old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
  1790. old.remove(ext)
  1791. header = cls._adjust_header(type_, header)
  1792. blockers = [name + x for x in old]
  1793. yield name + ext, header + script_text, 't', blockers
  1794. @staticmethod
  1795. def _adjust_header(type_, orig_header):
  1796. """
  1797. Make sure 'pythonw' is used for gui and and 'python' is used for
  1798. console (regardless of what sys.executable is).
  1799. """
  1800. pattern = 'pythonw.exe'
  1801. repl = 'python.exe'
  1802. if type_ == 'gui':
  1803. pattern, repl = repl, pattern
  1804. pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
  1805. new_header = pattern_ob.sub(string=orig_header, repl=repl)
  1806. clean_header = new_header[2:-1].strip('"')
  1807. if sys.platform == 'win32' and not os.path.exists(clean_header):
  1808. # the adjusted version doesn't exist, so return the original
  1809. return orig_header
  1810. return new_header
  1811. class WindowsExecutableLauncherWriter(WindowsScriptWriter):
  1812. @classmethod
  1813. def _get_script_args(cls, type_, name, header, script_text):
  1814. """
  1815. For Windows, add a .py extension and an .exe launcher
  1816. """
  1817. if type_ == 'gui':
  1818. launcher_type = 'gui'
  1819. ext = '-script.pyw'
  1820. old = ['.pyw']
  1821. else:
  1822. launcher_type = 'cli'
  1823. ext = '-script.py'
  1824. old = ['.py', '.pyc', '.pyo']
  1825. hdr = cls._adjust_header(type_, header)
  1826. blockers = [name + x for x in old]
  1827. yield (name + ext, hdr + script_text, 't', blockers)
  1828. yield (
  1829. name + '.exe', get_win_launcher(launcher_type),
  1830. 'b' # write in binary mode
  1831. )
  1832. if not is_64bit():
  1833. # install a manifest for the launcher to prevent Windows
  1834. # from detecting it as an installer (which it will for
  1835. # launchers like easy_install.exe). Consider only
  1836. # adding a manifest for launchers detected as installers.
  1837. # See Distribute #143 for details.
  1838. m_name = name + '.exe.manifest'
  1839. yield (m_name, load_launcher_manifest(name), 't')
  1840. # for backward-compatibility
  1841. get_script_args = ScriptWriter.get_script_args
  1842. get_script_header = ScriptWriter.get_script_header
  1843. def get_win_launcher(type):
  1844. """
  1845. Load the Windows launcher (executable) suitable for launching a script.
  1846. `type` should be either 'cli' or 'gui'
  1847. Returns the executable as a byte string.
  1848. """
  1849. launcher_fn = '%s.exe' % type
  1850. if platform.machine().lower() == 'arm':
  1851. launcher_fn = launcher_fn.replace(".", "-arm.")
  1852. if is_64bit():
  1853. launcher_fn = launcher_fn.replace(".", "-64.")
  1854. else:
  1855. launcher_fn = launcher_fn.replace(".", "-32.")
  1856. return resource_string('setuptools', launcher_fn)
  1857. def load_launcher_manifest(name):
  1858. manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
  1859. if PY2:
  1860. return manifest % vars()
  1861. else:
  1862. return manifest.decode('utf-8') % vars()
  1863. def rmtree(path, ignore_errors=False, onerror=auto_chmod):
  1864. """Recursively delete a directory tree.
  1865. This code is taken from the Python 2.4 version of 'shutil', because
  1866. the 2.3 version doesn't really work right.
  1867. """
  1868. if ignore_errors:
  1869. def onerror(*args):
  1870. pass
  1871. elif onerror is None:
  1872. def onerror(*args):
  1873. raise
  1874. names = []
  1875. try:
  1876. names = os.listdir(path)
  1877. except os.error:
  1878. onerror(os.listdir, path, sys.exc_info())
  1879. for name in names:
  1880. fullname = os.path.join(path, name)
  1881. try:
  1882. mode = os.lstat(fullname).st_mode
  1883. except os.error:
  1884. mode = 0
  1885. if stat.S_ISDIR(mode):
  1886. rmtree(fullname, ignore_errors, onerror)
  1887. else:
  1888. try:
  1889. os.remove(fullname)
  1890. except os.error:
  1891. onerror(os.remove, fullname, sys.exc_info())
  1892. try:
  1893. os.rmdir(path)
  1894. except os.error:
  1895. onerror(os.rmdir, path, sys.exc_info())
  1896. def current_umask():
  1897. tmp = os.umask(0o022)
  1898. os.umask(tmp)
  1899. return tmp
  1900. def bootstrap():
  1901. # This function is called when setuptools*.egg is run using /bin/sh
  1902. import setuptools
  1903. argv0 = os.path.dirname(setuptools.__path__[0])
  1904. sys.argv[0] = argv0
  1905. sys.argv.append(argv0)
  1906. main()
  1907. def main(argv=None, **kw):
  1908. from setuptools import setup
  1909. from setuptools.dist import Distribution
  1910. class DistributionWithoutHelpCommands(Distribution):
  1911. common_usage = ""
  1912. def _show_help(self, *args, **kw):
  1913. with _patch_usage():
  1914. Distribution._show_help(self, *args, **kw)
  1915. if argv is None:
  1916. argv = sys.argv[1:]
  1917. with _patch_usage():
  1918. setup(
  1919. script_args=['-q', 'easy_install', '-v'] + argv,
  1920. script_name=sys.argv[0] or 'easy_install',
  1921. distclass=DistributionWithoutHelpCommands, **kw
  1922. )
  1923. @contextlib.contextmanager
  1924. def _patch_usage():
  1925. import distutils.core
  1926. USAGE = textwrap.dedent("""
  1927. usage: %(script)s [options] requirement_or_url ...
  1928. or: %(script)s --help
  1929. """).lstrip()
  1930. def gen_usage(script_name):
  1931. return USAGE % dict(
  1932. script=os.path.basename(script_name),
  1933. )
  1934. saved = distutils.core.gen_usage
  1935. distutils.core.gen_usage = gen_usage
  1936. try:
  1937. yield
  1938. finally:
  1939. distutils.core.gen_usage = saved