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.

2342 lines
85 KiB

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