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.

3289 lines
106KB

  1. """
  2. Package resource API
  3. --------------------
  4. A resource is a logical file contained within a package, or a logical
  5. subdirectory thereof. The package resource API expects resource names
  6. to have their path parts separated with ``/``, *not* whatever the local
  7. path separator is. Do not use os.path operations to manipulate resource
  8. names being passed into the API.
  9. The package resource API is designed to work with normal filesystem packages,
  10. .egg files, and unpacked .egg files. It can also work in a limited way with
  11. .zip files and with custom PEP 302 loaders that support the ``get_data()``
  12. method.
  13. """
  14. import sys
  15. import os
  16. import io
  17. import time
  18. import re
  19. import types
  20. import zipfile
  21. import zipimport
  22. import warnings
  23. import stat
  24. import functools
  25. import pkgutil
  26. import operator
  27. import platform
  28. import collections
  29. import plistlib
  30. import email.parser
  31. import errno
  32. import tempfile
  33. import textwrap
  34. import itertools
  35. import inspect
  36. import ntpath
  37. import posixpath
  38. import importlib
  39. from pkgutil import get_importer
  40. try:
  41. import _imp
  42. except ImportError:
  43. # Python 3.2 compatibility
  44. import imp as _imp
  45. try:
  46. FileExistsError
  47. except NameError:
  48. FileExistsError = OSError
  49. # capture these to bypass sandboxing
  50. from os import utime
  51. try:
  52. from os import mkdir, rename, unlink
  53. WRITE_SUPPORT = True
  54. except ImportError:
  55. # no write support, probably under GAE
  56. WRITE_SUPPORT = False
  57. from os import open as os_open
  58. from os.path import isdir, split
  59. try:
  60. import importlib.machinery as importlib_machinery
  61. # access attribute to force import under delayed import mechanisms.
  62. importlib_machinery.__name__
  63. except ImportError:
  64. importlib_machinery = None
  65. from pkg_resources.extern import appdirs
  66. from pkg_resources.extern import packaging
  67. __import__('pkg_resources.extern.packaging.version')
  68. __import__('pkg_resources.extern.packaging.specifiers')
  69. __import__('pkg_resources.extern.packaging.requirements')
  70. __import__('pkg_resources.extern.packaging.markers')
  71. if sys.version_info < (3, 5):
  72. raise RuntimeError("Python 3.5 or later is required")
  73. # declare some globals that will be defined later to
  74. # satisfy the linters.
  75. require = None
  76. working_set = None
  77. add_activation_listener = None
  78. resources_stream = None
  79. cleanup_resources = None
  80. resource_dir = None
  81. resource_stream = None
  82. set_extraction_path = None
  83. resource_isdir = None
  84. resource_string = None
  85. iter_entry_points = None
  86. resource_listdir = None
  87. resource_filename = None
  88. resource_exists = None
  89. _distribution_finders = None
  90. _namespace_handlers = None
  91. _namespace_packages = None
  92. class PEP440Warning(RuntimeWarning):
  93. """
  94. Used when there is an issue with a version or specifier not complying with
  95. PEP 440.
  96. """
  97. def parse_version(v):
  98. try:
  99. return packaging.version.Version(v)
  100. except packaging.version.InvalidVersion:
  101. return packaging.version.LegacyVersion(v)
  102. _state_vars = {}
  103. def _declare_state(vartype, **kw):
  104. globals().update(kw)
  105. _state_vars.update(dict.fromkeys(kw, vartype))
  106. def __getstate__():
  107. state = {}
  108. g = globals()
  109. for k, v in _state_vars.items():
  110. state[k] = g['_sget_' + v](g[k])
  111. return state
  112. def __setstate__(state):
  113. g = globals()
  114. for k, v in state.items():
  115. g['_sset_' + _state_vars[k]](k, g[k], v)
  116. return state
  117. def _sget_dict(val):
  118. return val.copy()
  119. def _sset_dict(key, ob, state):
  120. ob.clear()
  121. ob.update(state)
  122. def _sget_object(val):
  123. return val.__getstate__()
  124. def _sset_object(key, ob, state):
  125. ob.__setstate__(state)
  126. _sget_none = _sset_none = lambda *args: None
  127. def get_supported_platform():
  128. """Return this platform's maximum compatible version.
  129. distutils.util.get_platform() normally reports the minimum version
  130. of macOS that would be required to *use* extensions produced by
  131. distutils. But what we want when checking compatibility is to know the
  132. version of macOS that we are *running*. To allow usage of packages that
  133. explicitly require a newer version of macOS, we must also know the
  134. current version of the OS.
  135. If this condition occurs for any other platform with a version in its
  136. platform strings, this function should be extended accordingly.
  137. """
  138. plat = get_build_platform()
  139. m = macosVersionString.match(plat)
  140. if m is not None and sys.platform == "darwin":
  141. try:
  142. plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
  143. except ValueError:
  144. # not macOS
  145. pass
  146. return plat
  147. __all__ = [
  148. # Basic resource access and distribution/entry point discovery
  149. 'require', 'run_script', 'get_provider', 'get_distribution',
  150. 'load_entry_point', 'get_entry_map', 'get_entry_info',
  151. 'iter_entry_points',
  152. 'resource_string', 'resource_stream', 'resource_filename',
  153. 'resource_listdir', 'resource_exists', 'resource_isdir',
  154. # Environmental control
  155. 'declare_namespace', 'working_set', 'add_activation_listener',
  156. 'find_distributions', 'set_extraction_path', 'cleanup_resources',
  157. 'get_default_cache',
  158. # Primary implementation classes
  159. 'Environment', 'WorkingSet', 'ResourceManager',
  160. 'Distribution', 'Requirement', 'EntryPoint',
  161. # Exceptions
  162. 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
  163. 'UnknownExtra', 'ExtractionError',
  164. # Warnings
  165. 'PEP440Warning',
  166. # Parsing functions and string utilities
  167. 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
  168. 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
  169. 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
  170. # filesystem utilities
  171. 'ensure_directory', 'normalize_path',
  172. # Distribution "precedence" constants
  173. 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
  174. # "Provider" interfaces, implementations, and registration/lookup APIs
  175. 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
  176. 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
  177. 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
  178. 'register_finder', 'register_namespace_handler', 'register_loader_type',
  179. 'fixup_namespace_packages', 'get_importer',
  180. # Warnings
  181. 'PkgResourcesDeprecationWarning',
  182. # Deprecated/backward compatibility only
  183. 'run_main', 'AvailableDistributions',
  184. ]
  185. class ResolutionError(Exception):
  186. """Abstract base for dependency resolution errors"""
  187. def __repr__(self):
  188. return self.__class__.__name__ + repr(self.args)
  189. class VersionConflict(ResolutionError):
  190. """
  191. An already-installed version conflicts with the requested version.
  192. Should be initialized with the installed Distribution and the requested
  193. Requirement.
  194. """
  195. _template = "{self.dist} is installed but {self.req} is required"
  196. @property
  197. def dist(self):
  198. return self.args[0]
  199. @property
  200. def req(self):
  201. return self.args[1]
  202. def report(self):
  203. return self._template.format(**locals())
  204. def with_context(self, required_by):
  205. """
  206. If required_by is non-empty, return a version of self that is a
  207. ContextualVersionConflict.
  208. """
  209. if not required_by:
  210. return self
  211. args = self.args + (required_by,)
  212. return ContextualVersionConflict(*args)
  213. class ContextualVersionConflict(VersionConflict):
  214. """
  215. A VersionConflict that accepts a third parameter, the set of the
  216. requirements that required the installed Distribution.
  217. """
  218. _template = VersionConflict._template + ' by {self.required_by}'
  219. @property
  220. def required_by(self):
  221. return self.args[2]
  222. class DistributionNotFound(ResolutionError):
  223. """A requested distribution was not found"""
  224. _template = ("The '{self.req}' distribution was not found "
  225. "and is required by {self.requirers_str}")
  226. @property
  227. def req(self):
  228. return self.args[0]
  229. @property
  230. def requirers(self):
  231. return self.args[1]
  232. @property
  233. def requirers_str(self):
  234. if not self.requirers:
  235. return 'the application'
  236. return ', '.join(self.requirers)
  237. def report(self):
  238. return self._template.format(**locals())
  239. def __str__(self):
  240. return self.report()
  241. class UnknownExtra(ResolutionError):
  242. """Distribution doesn't have an "extra feature" of the given name"""
  243. _provider_factories = {}
  244. PY_MAJOR = '{}.{}'.format(*sys.version_info)
  245. EGG_DIST = 3
  246. BINARY_DIST = 2
  247. SOURCE_DIST = 1
  248. CHECKOUT_DIST = 0
  249. DEVELOP_DIST = -1
  250. def register_loader_type(loader_type, provider_factory):
  251. """Register `provider_factory` to make providers for `loader_type`
  252. `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
  253. and `provider_factory` is a function that, passed a *module* object,
  254. returns an ``IResourceProvider`` for that module.
  255. """
  256. _provider_factories[loader_type] = provider_factory
  257. def get_provider(moduleOrReq):
  258. """Return an IResourceProvider for the named module or requirement"""
  259. if isinstance(moduleOrReq, Requirement):
  260. return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  261. try:
  262. module = sys.modules[moduleOrReq]
  263. except KeyError:
  264. __import__(moduleOrReq)
  265. module = sys.modules[moduleOrReq]
  266. loader = getattr(module, '__loader__', None)
  267. return _find_adapter(_provider_factories, loader)(module)
  268. def _macos_vers(_cache=[]):
  269. if not _cache:
  270. version = platform.mac_ver()[0]
  271. # fallback for MacPorts
  272. if version == '':
  273. plist = '/System/Library/CoreServices/SystemVersion.plist'
  274. if os.path.exists(plist):
  275. if hasattr(plistlib, 'readPlist'):
  276. plist_content = plistlib.readPlist(plist)
  277. if 'ProductVersion' in plist_content:
  278. version = plist_content['ProductVersion']
  279. _cache.append(version.split('.'))
  280. return _cache[0]
  281. def _macos_arch(machine):
  282. return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
  283. def get_build_platform():
  284. """Return this platform's string for platform-specific distributions
  285. XXX Currently this is the same as ``distutils.util.get_platform()``, but it
  286. needs some hacks for Linux and macOS.
  287. """
  288. from sysconfig import get_platform
  289. plat = get_platform()
  290. if sys.platform == "darwin" and not plat.startswith('macosx-'):
  291. try:
  292. version = _macos_vers()
  293. machine = os.uname()[4].replace(" ", "_")
  294. return "macosx-%d.%d-%s" % (
  295. int(version[0]), int(version[1]),
  296. _macos_arch(machine),
  297. )
  298. except ValueError:
  299. # if someone is running a non-Mac darwin system, this will fall
  300. # through to the default implementation
  301. pass
  302. return plat
  303. macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
  304. darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
  305. # XXX backward compat
  306. get_platform = get_build_platform
  307. def compatible_platforms(provided, required):
  308. """Can code for the `provided` platform run on the `required` platform?
  309. Returns true if either platform is ``None``, or the platforms are equal.
  310. XXX Needs compatibility checks for Linux and other unixy OSes.
  311. """
  312. if provided is None or required is None or provided == required:
  313. # easy case
  314. return True
  315. # macOS special cases
  316. reqMac = macosVersionString.match(required)
  317. if reqMac:
  318. provMac = macosVersionString.match(provided)
  319. # is this a Mac package?
  320. if not provMac:
  321. # this is backwards compatibility for packages built before
  322. # setuptools 0.6. All packages built after this point will
  323. # use the new macOS designation.
  324. provDarwin = darwinVersionString.match(provided)
  325. if provDarwin:
  326. dversion = int(provDarwin.group(1))
  327. macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
  328. if dversion == 7 and macosversion >= "10.3" or \
  329. dversion == 8 and macosversion >= "10.4":
  330. return True
  331. # egg isn't macOS or legacy darwin
  332. return False
  333. # are they the same major version and machine type?
  334. if provMac.group(1) != reqMac.group(1) or \
  335. provMac.group(3) != reqMac.group(3):
  336. return False
  337. # is the required OS major update >= the provided one?
  338. if int(provMac.group(2)) > int(reqMac.group(2)):
  339. return False
  340. return True
  341. # XXX Linux and other platforms' special cases should go here
  342. return False
  343. def run_script(dist_spec, script_name):
  344. """Locate distribution `dist_spec` and run its `script_name` script"""
  345. ns = sys._getframe(1).f_globals
  346. name = ns['__name__']
  347. ns.clear()
  348. ns['__name__'] = name
  349. require(dist_spec)[0].run_script(script_name, ns)
  350. # backward compatibility
  351. run_main = run_script
  352. def get_distribution(dist):
  353. """Return a current distribution object for a Requirement or string"""
  354. if isinstance(dist, str):
  355. dist = Requirement.parse(dist)
  356. if isinstance(dist, Requirement):
  357. dist = get_provider(dist)
  358. if not isinstance(dist, Distribution):
  359. raise TypeError("Expected string, Requirement, or Distribution", dist)
  360. return dist
  361. def load_entry_point(dist, group, name):
  362. """Return `name` entry point of `group` for `dist` or raise ImportError"""
  363. return get_distribution(dist).load_entry_point(group, name)
  364. def get_entry_map(dist, group=None):
  365. """Return the entry point map for `group`, or the full entry map"""
  366. return get_distribution(dist).get_entry_map(group)
  367. def get_entry_info(dist, group, name):
  368. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  369. return get_distribution(dist).get_entry_info(group, name)
  370. class IMetadataProvider:
  371. def has_metadata(name):
  372. """Does the package's distribution contain the named metadata?"""
  373. def get_metadata(name):
  374. """The named metadata resource as a string"""
  375. def get_metadata_lines(name):
  376. """Yield named metadata resource as list of non-blank non-comment lines
  377. Leading and trailing whitespace is stripped from each line, and lines
  378. with ``#`` as the first non-blank character are omitted."""
  379. def metadata_isdir(name):
  380. """Is the named metadata a directory? (like ``os.path.isdir()``)"""
  381. def metadata_listdir(name):
  382. """List of metadata names in the directory (like ``os.listdir()``)"""
  383. def run_script(script_name, namespace):
  384. """Execute the named script in the supplied namespace dictionary"""
  385. class IResourceProvider(IMetadataProvider):
  386. """An object that provides access to package resources"""
  387. def get_resource_filename(manager, resource_name):
  388. """Return a true filesystem path for `resource_name`
  389. `manager` must be an ``IResourceManager``"""
  390. def get_resource_stream(manager, resource_name):
  391. """Return a readable file-like object for `resource_name`
  392. `manager` must be an ``IResourceManager``"""
  393. def get_resource_string(manager, resource_name):
  394. """Return a string containing the contents of `resource_name`
  395. `manager` must be an ``IResourceManager``"""
  396. def has_resource(resource_name):
  397. """Does the package contain the named resource?"""
  398. def resource_isdir(resource_name):
  399. """Is the named resource a directory? (like ``os.path.isdir()``)"""
  400. def resource_listdir(resource_name):
  401. """List of resource names in the directory (like ``os.listdir()``)"""
  402. class WorkingSet:
  403. """A collection of active distributions on sys.path (or a similar list)"""
  404. def __init__(self, entries=None):
  405. """Create working set from list of path entries (default=sys.path)"""
  406. self.entries = []
  407. self.entry_keys = {}
  408. self.by_key = {}
  409. self.callbacks = []
  410. if entries is None:
  411. entries = sys.path
  412. for entry in entries:
  413. self.add_entry(entry)
  414. @classmethod
  415. def _build_master(cls):
  416. """
  417. Prepare the master working set.
  418. """
  419. ws = cls()
  420. try:
  421. from __main__ import __requires__
  422. except ImportError:
  423. # The main program does not list any requirements
  424. return ws
  425. # ensure the requirements are met
  426. try:
  427. ws.require(__requires__)
  428. except VersionConflict:
  429. return cls._build_from_requirements(__requires__)
  430. return ws
  431. @classmethod
  432. def _build_from_requirements(cls, req_spec):
  433. """
  434. Build a working set from a requirement spec. Rewrites sys.path.
  435. """
  436. # try it without defaults already on sys.path
  437. # by starting with an empty path
  438. ws = cls([])
  439. reqs = parse_requirements(req_spec)
  440. dists = ws.resolve(reqs, Environment())
  441. for dist in dists:
  442. ws.add(dist)
  443. # add any missing entries from sys.path
  444. for entry in sys.path:
  445. if entry not in ws.entries:
  446. ws.add_entry(entry)
  447. # then copy back to sys.path
  448. sys.path[:] = ws.entries
  449. return ws
  450. def add_entry(self, entry):
  451. """Add a path item to ``.entries``, finding any distributions on it
  452. ``find_distributions(entry, True)`` is used to find distributions
  453. corresponding to the path entry, and they are added. `entry` is
  454. always appended to ``.entries``, even if it is already present.
  455. (This is because ``sys.path`` can contain the same value more than
  456. once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
  457. equal ``sys.path``.)
  458. """
  459. self.entry_keys.setdefault(entry, [])
  460. self.entries.append(entry)
  461. for dist in find_distributions(entry, True):
  462. self.add(dist, entry, False)
  463. def __contains__(self, dist):
  464. """True if `dist` is the active distribution for its project"""
  465. return self.by_key.get(dist.key) == dist
  466. def find(self, req):
  467. """Find a distribution matching requirement `req`
  468. If there is an active distribution for the requested project, this
  469. returns it as long as it meets the version requirement specified by
  470. `req`. But, if there is an active distribution for the project and it
  471. does *not* meet the `req` requirement, ``VersionConflict`` is raised.
  472. If there is no active distribution for the requested project, ``None``
  473. is returned.
  474. """
  475. dist = self.by_key.get(req.key)
  476. if dist is not None and dist not in req:
  477. # XXX add more info
  478. raise VersionConflict(dist, req)
  479. return dist
  480. def iter_entry_points(self, group, name=None):
  481. """Yield entry point objects from `group` matching `name`
  482. If `name` is None, yields all entry points in `group` from all
  483. distributions in the working set, otherwise only ones matching
  484. both `group` and `name` are yielded (in distribution order).
  485. """
  486. return (
  487. entry
  488. for dist in self
  489. for entry in dist.get_entry_map(group).values()
  490. if name is None or name == entry.name
  491. )
  492. def run_script(self, requires, script_name):
  493. """Locate distribution for `requires` and run `script_name` script"""
  494. ns = sys._getframe(1).f_globals
  495. name = ns['__name__']
  496. ns.clear()
  497. ns['__name__'] = name
  498. self.require(requires)[0].run_script(script_name, ns)
  499. def __iter__(self):
  500. """Yield distributions for non-duplicate projects in the working set
  501. The yield order is the order in which the items' path entries were
  502. added to the working set.
  503. """
  504. seen = {}
  505. for item in self.entries:
  506. if item not in self.entry_keys:
  507. # workaround a cache issue
  508. continue
  509. for key in self.entry_keys[item]:
  510. if key not in seen:
  511. seen[key] = 1
  512. yield self.by_key[key]
  513. def add(self, dist, entry=None, insert=True, replace=False):
  514. """Add `dist` to working set, associated with `entry`
  515. If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
  516. On exit from this routine, `entry` is added to the end of the working
  517. set's ``.entries`` (if it wasn't already present).
  518. `dist` is only added to the working set if it's for a project that
  519. doesn't already have a distribution in the set, unless `replace=True`.
  520. If it's added, any callbacks registered with the ``subscribe()`` method
  521. will be called.
  522. """
  523. if insert:
  524. dist.insert_on(self.entries, entry, replace=replace)
  525. if entry is None:
  526. entry = dist.location
  527. keys = self.entry_keys.setdefault(entry, [])
  528. keys2 = self.entry_keys.setdefault(dist.location, [])
  529. if not replace and dist.key in self.by_key:
  530. # ignore hidden distros
  531. return
  532. self.by_key[dist.key] = dist
  533. if dist.key not in keys:
  534. keys.append(dist.key)
  535. if dist.key not in keys2:
  536. keys2.append(dist.key)
  537. self._added_new(dist)
  538. # FIXME: 'WorkingSet.resolve' is too complex (11)
  539. def resolve(self, requirements, env=None, installer=None, # noqa: C901
  540. replace_conflicting=False, extras=None):
  541. """List all distributions needed to (recursively) meet `requirements`
  542. `requirements` must be a sequence of ``Requirement`` objects. `env`,
  543. if supplied, should be an ``Environment`` instance. If
  544. not supplied, it defaults to all distributions available within any
  545. entry or distribution in the working set. `installer`, if supplied,
  546. will be invoked with each requirement that cannot be met by an
  547. already-installed distribution; it should return a ``Distribution`` or
  548. ``None``.
  549. Unless `replace_conflicting=True`, raises a VersionConflict exception
  550. if
  551. any requirements are found on the path that have the correct name but
  552. the wrong version. Otherwise, if an `installer` is supplied it will be
  553. invoked to obtain the correct version of the requirement and activate
  554. it.
  555. `extras` is a list of the extras to be used with these requirements.
  556. This is important because extra requirements may look like `my_req;
  557. extra = "my_extra"`, which would otherwise be interpreted as a purely
  558. optional requirement. Instead, we want to be able to assert that these
  559. requirements are truly required.
  560. """
  561. # set up the stack
  562. requirements = list(requirements)[::-1]
  563. # set of processed requirements
  564. processed = {}
  565. # key -> dist
  566. best = {}
  567. to_activate = []
  568. req_extras = _ReqExtras()
  569. # Mapping of requirement to set of distributions that required it;
  570. # useful for reporting info about conflicts.
  571. required_by = collections.defaultdict(set)
  572. while requirements:
  573. # process dependencies breadth-first
  574. req = requirements.pop(0)
  575. if req in processed:
  576. # Ignore cyclic or redundant dependencies
  577. continue
  578. if not req_extras.markers_pass(req, extras):
  579. continue
  580. dist = best.get(req.key)
  581. if dist is None:
  582. # Find the best distribution and add it to the map
  583. dist = self.by_key.get(req.key)
  584. if dist is None or (dist not in req and replace_conflicting):
  585. ws = self
  586. if env is None:
  587. if dist is None:
  588. env = Environment(self.entries)
  589. else:
  590. # Use an empty environment and workingset to avoid
  591. # any further conflicts with the conflicting
  592. # distribution
  593. env = Environment([])
  594. ws = WorkingSet([])
  595. dist = best[req.key] = env.best_match(
  596. req, ws, installer,
  597. replace_conflicting=replace_conflicting
  598. )
  599. if dist is None:
  600. requirers = required_by.get(req, None)
  601. raise DistributionNotFound(req, requirers)
  602. to_activate.append(dist)
  603. if dist not in req:
  604. # Oops, the "best" so far conflicts with a dependency
  605. dependent_req = required_by[req]
  606. raise VersionConflict(dist, req).with_context(dependent_req)
  607. # push the new requirements onto the stack
  608. new_requirements = dist.requires(req.extras)[::-1]
  609. requirements.extend(new_requirements)
  610. # Register the new requirements needed by req
  611. for new_requirement in new_requirements:
  612. required_by[new_requirement].add(req.project_name)
  613. req_extras[new_requirement] = req.extras
  614. processed[req] = True
  615. # return list of distros to activate
  616. return to_activate
  617. def find_plugins(
  618. self, plugin_env, full_env=None, installer=None, fallback=True):
  619. """Find all activatable distributions in `plugin_env`
  620. Example usage::
  621. distributions, errors = working_set.find_plugins(
  622. Environment(plugin_dirlist)
  623. )
  624. # add plugins+libs to sys.path
  625. map(working_set.add, distributions)
  626. # display errors
  627. print('Could not load', errors)
  628. The `plugin_env` should be an ``Environment`` instance that contains
  629. only distributions that are in the project's "plugin directory" or
  630. directories. The `full_env`, if supplied, should be an ``Environment``
  631. contains all currently-available distributions. If `full_env` is not
  632. supplied, one is created automatically from the ``WorkingSet`` this
  633. method is called on, which will typically mean that every directory on
  634. ``sys.path`` will be scanned for distributions.
  635. `installer` is a standard installer callback as used by the
  636. ``resolve()`` method. The `fallback` flag indicates whether we should
  637. attempt to resolve older versions of a plugin if the newest version
  638. cannot be resolved.
  639. This method returns a 2-tuple: (`distributions`, `error_info`), where
  640. `distributions` is a list of the distributions found in `plugin_env`
  641. that were loadable, along with any other distributions that are needed
  642. to resolve their dependencies. `error_info` is a dictionary mapping
  643. unloadable plugin distributions to an exception instance describing the
  644. error that occurred. Usually this will be a ``DistributionNotFound`` or
  645. ``VersionConflict`` instance.
  646. """
  647. plugin_projects = list(plugin_env)
  648. # scan project names in alphabetic order
  649. plugin_projects.sort()
  650. error_info = {}
  651. distributions = {}
  652. if full_env is None:
  653. env = Environment(self.entries)
  654. env += plugin_env
  655. else:
  656. env = full_env + plugin_env
  657. shadow_set = self.__class__([])
  658. # put all our entries in shadow_set
  659. list(map(shadow_set.add, self))
  660. for project_name in plugin_projects:
  661. for dist in plugin_env[project_name]:
  662. req = [dist.as_requirement()]
  663. try:
  664. resolvees = shadow_set.resolve(req, env, installer)
  665. except ResolutionError as v:
  666. # save error info
  667. error_info[dist] = v
  668. if fallback:
  669. # try the next older version of project
  670. continue
  671. else:
  672. # give up on this project, keep going
  673. break
  674. else:
  675. list(map(shadow_set.add, resolvees))
  676. distributions.update(dict.fromkeys(resolvees))
  677. # success, no need to try any more versions of this project
  678. break
  679. distributions = list(distributions)
  680. distributions.sort()
  681. return distributions, error_info
  682. def require(self, *requirements):
  683. """Ensure that distributions matching `requirements` are activated
  684. `requirements` must be a string or a (possibly-nested) sequence
  685. thereof, specifying the distributions and versions required. The
  686. return value is a sequence of the distributions that needed to be
  687. activated to fulfill the requirements; all relevant distributions are
  688. included, even if they were already activated in this working set.
  689. """
  690. needed = self.resolve(parse_requirements(requirements))
  691. for dist in needed:
  692. self.add(dist)
  693. return needed
  694. def subscribe(self, callback, existing=True):
  695. """Invoke `callback` for all distributions
  696. If `existing=True` (default),
  697. call on all existing ones, as well.
  698. """
  699. if callback in self.callbacks:
  700. return
  701. self.callbacks.append(callback)
  702. if not existing:
  703. return
  704. for dist in self:
  705. callback(dist)
  706. def _added_new(self, dist):
  707. for callback in self.callbacks:
  708. callback(dist)
  709. def __getstate__(self):
  710. return (
  711. self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
  712. self.callbacks[:]
  713. )
  714. def __setstate__(self, e_k_b_c):
  715. entries, keys, by_key, callbacks = e_k_b_c
  716. self.entries = entries[:]
  717. self.entry_keys = keys.copy()
  718. self.by_key = by_key.copy()
  719. self.callbacks = callbacks[:]
  720. class _ReqExtras(dict):
  721. """
  722. Map each requirement to the extras that demanded it.
  723. """
  724. def markers_pass(self, req, extras=None):
  725. """
  726. Evaluate markers for req against each extra that
  727. demanded it.
  728. Return False if the req has a marker and fails
  729. evaluation. Otherwise, return True.
  730. """
  731. extra_evals = (
  732. req.marker.evaluate({'extra': extra})
  733. for extra in self.get(req, ()) + (extras or (None,))
  734. )
  735. return not req.marker or any(extra_evals)
  736. class Environment:
  737. """Searchable snapshot of distributions on a search path"""
  738. def __init__(
  739. self, search_path=None, platform=get_supported_platform(),
  740. python=PY_MAJOR):
  741. """Snapshot distributions available on a search path
  742. Any distributions found on `search_path` are added to the environment.
  743. `search_path` should be a sequence of ``sys.path`` items. If not
  744. supplied, ``sys.path`` is used.
  745. `platform` is an optional string specifying the name of the platform
  746. that platform-specific distributions must be compatible with. If
  747. unspecified, it defaults to the current platform. `python` is an
  748. optional string naming the desired version of Python (e.g. ``'3.6'``);
  749. it defaults to the current version.
  750. You may explicitly set `platform` (and/or `python`) to ``None`` if you
  751. wish to map *all* distributions, not just those compatible with the
  752. running platform or Python version.
  753. """
  754. self._distmap = {}
  755. self.platform = platform
  756. self.python = python
  757. self.scan(search_path)
  758. def can_add(self, dist):
  759. """Is distribution `dist` acceptable for this environment?
  760. The distribution must match the platform and python version
  761. requirements specified when this environment was created, or False
  762. is returned.
  763. """
  764. py_compat = (
  765. self.python is None
  766. or dist.py_version is None
  767. or dist.py_version == self.python
  768. )
  769. return py_compat and compatible_platforms(dist.platform, self.platform)
  770. def remove(self, dist):
  771. """Remove `dist` from the environment"""
  772. self._distmap[dist.key].remove(dist)
  773. def scan(self, search_path=None):
  774. """Scan `search_path` for distributions usable in this environment
  775. Any distributions found are added to the environment.
  776. `search_path` should be a sequence of ``sys.path`` items. If not
  777. supplied, ``sys.path`` is used. Only distributions conforming to
  778. the platform/python version defined at initialization are added.
  779. """
  780. if search_path is None:
  781. search_path = sys.path
  782. for item in search_path:
  783. for dist in find_distributions(item):
  784. self.add(dist)
  785. def __getitem__(self, project_name):
  786. """Return a newest-to-oldest list of distributions for `project_name`
  787. Uses case-insensitive `project_name` comparison, assuming all the
  788. project's distributions use their project's name converted to all
  789. lowercase as their key.
  790. """
  791. distribution_key = project_name.lower()
  792. return self._distmap.get(distribution_key, [])
  793. def add(self, dist):
  794. """Add `dist` if we ``can_add()`` it and it has not already been added
  795. """
  796. if self.can_add(dist) and dist.has_version():
  797. dists = self._distmap.setdefault(dist.key, [])
  798. if dist not in dists:
  799. dists.append(dist)
  800. dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
  801. def best_match(
  802. self, req, working_set, installer=None, replace_conflicting=False):
  803. """Find distribution best matching `req` and usable on `working_set`
  804. This calls the ``find(req)`` method of the `working_set` to see if a
  805. suitable distribution is already active. (This may raise
  806. ``VersionConflict`` if an unsuitable version of the project is already
  807. active in the specified `working_set`.) If a suitable distribution
  808. isn't active, this method returns the newest distribution in the
  809. environment that meets the ``Requirement`` in `req`. If no suitable
  810. distribution is found, and `installer` is supplied, then the result of
  811. calling the environment's ``obtain(req, installer)`` method will be
  812. returned.
  813. """
  814. try:
  815. dist = working_set.find(req)
  816. except VersionConflict:
  817. if not replace_conflicting:
  818. raise
  819. dist = None
  820. if dist is not None:
  821. return dist
  822. for dist in self[req.key]:
  823. if dist in req:
  824. return dist
  825. # try to download/install
  826. return self.obtain(req, installer)
  827. def obtain(self, requirement, installer=None):
  828. """Obtain a distribution matching `requirement` (e.g. via download)
  829. Obtain a distro that matches requirement (e.g. via download). In the
  830. base ``Environment`` class, this routine just returns
  831. ``installer(requirement)``, unless `installer` is None, in which case
  832. None is returned instead. This method is a hook that allows subclasses
  833. to attempt other ways of obtaining a distribution before falling back
  834. to the `installer` argument."""
  835. if installer is not None:
  836. return installer(requirement)
  837. def __iter__(self):
  838. """Yield the unique project names of the available distributions"""
  839. for key in self._distmap.keys():
  840. if self[key]:
  841. yield key
  842. def __iadd__(self, other):
  843. """In-place addition of a distribution or environment"""
  844. if isinstance(other, Distribution):
  845. self.add(other)
  846. elif isinstance(other, Environment):
  847. for project in other:
  848. for dist in other[project]:
  849. self.add(dist)
  850. else:
  851. raise TypeError("Can't add %r to environment" % (other,))
  852. return self
  853. def __add__(self, other):
  854. """Add an environment or distribution to an environment"""
  855. new = self.__class__([], platform=None, python=None)
  856. for env in self, other:
  857. new += env
  858. return new
  859. # XXX backward compatibility
  860. AvailableDistributions = Environment
  861. class ExtractionError(RuntimeError):
  862. """An error occurred extracting a resource
  863. The following attributes are available from instances of this exception:
  864. manager
  865. The resource manager that raised this exception
  866. cache_path
  867. The base directory for resource extraction
  868. original_error
  869. The exception instance that caused extraction to fail
  870. """
  871. class ResourceManager:
  872. """Manage resource extraction and packages"""
  873. extraction_path = None
  874. def __init__(self):
  875. self.cached_files = {}
  876. def resource_exists(self, package_or_requirement, resource_name):
  877. """Does the named resource exist?"""
  878. return get_provider(package_or_requirement).has_resource(resource_name)
  879. def resource_isdir(self, package_or_requirement, resource_name):
  880. """Is the named resource an existing directory?"""
  881. return get_provider(package_or_requirement).resource_isdir(
  882. resource_name
  883. )
  884. def resource_filename(self, package_or_requirement, resource_name):
  885. """Return a true filesystem path for specified resource"""
  886. return get_provider(package_or_requirement).get_resource_filename(
  887. self, resource_name
  888. )
  889. def resource_stream(self, package_or_requirement, resource_name):
  890. """Return a readable file-like object for specified resource"""
  891. return get_provider(package_or_requirement).get_resource_stream(
  892. self, resource_name
  893. )
  894. def resource_string(self, package_or_requirement, resource_name):
  895. """Return specified resource as a string"""
  896. return get_provider(package_or_requirement).get_resource_string(
  897. self, resource_name
  898. )
  899. def resource_listdir(self, package_or_requirement, resource_name):
  900. """List the contents of the named resource directory"""
  901. return get_provider(package_or_requirement).resource_listdir(
  902. resource_name
  903. )
  904. def extraction_error(self):
  905. """Give an error message for problems extracting file(s)"""
  906. old_exc = sys.exc_info()[1]
  907. cache_path = self.extraction_path or get_default_cache()
  908. tmpl = textwrap.dedent("""
  909. Can't extract file(s) to egg cache
  910. The following error occurred while trying to extract file(s)
  911. to the Python egg cache:
  912. {old_exc}
  913. The Python egg cache directory is currently set to:
  914. {cache_path}
  915. Perhaps your account does not have write access to this directory?
  916. You can change the cache directory by setting the PYTHON_EGG_CACHE
  917. environment variable to point to an accessible directory.
  918. """).lstrip()
  919. err = ExtractionError(tmpl.format(**locals()))
  920. err.manager = self
  921. err.cache_path = cache_path
  922. err.original_error = old_exc
  923. raise err
  924. def get_cache_path(self, archive_name, names=()):
  925. """Return absolute location in cache for `archive_name` and `names`
  926. The parent directory of the resulting path will be created if it does
  927. not already exist. `archive_name` should be the base filename of the
  928. enclosing egg (which may not be the name of the enclosing zipfile!),
  929. including its ".egg" extension. `names`, if provided, should be a
  930. sequence of path name parts "under" the egg's extraction location.
  931. This method should only be called by resource providers that need to
  932. obtain an extraction location, and only for names they intend to
  933. extract, as it tracks the generated names for possible cleanup later.
  934. """
  935. extract_path = self.extraction_path or get_default_cache()
  936. target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
  937. try:
  938. _bypass_ensure_directory(target_path)
  939. except Exception:
  940. self.extraction_error()
  941. self._warn_unsafe_extraction_path(extract_path)
  942. self.cached_files[target_path] = 1
  943. return target_path
  944. @staticmethod
  945. def _warn_unsafe_extraction_path(path):
  946. """
  947. If the default extraction path is overridden and set to an insecure
  948. location, such as /tmp, it opens up an opportunity for an attacker to
  949. replace an extracted file with an unauthorized payload. Warn the user
  950. if a known insecure location is used.
  951. See Distribute #375 for more details.
  952. """
  953. if os.name == 'nt' and not path.startswith(os.environ['windir']):
  954. # On Windows, permissions are generally restrictive by default
  955. # and temp directories are not writable by other users, so
  956. # bypass the warning.
  957. return
  958. mode = os.stat(path).st_mode
  959. if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
  960. msg = (
  961. "Extraction path is writable by group/others "
  962. "and vulnerable to attack when "
  963. "used with get_resource_filename ({path}). "
  964. "Consider a more secure "
  965. "location (set with .set_extraction_path or the "
  966. "PYTHON_EGG_CACHE environment variable)."
  967. ).format(**locals())
  968. warnings.warn(msg, UserWarning)
  969. def postprocess(self, tempname, filename):
  970. """Perform any platform-specific postprocessing of `tempname`
  971. This is where Mac header rewrites should be done; other platforms don't
  972. have anything special they should do.
  973. Resource providers should call this method ONLY after successfully
  974. extracting a compressed resource. They must NOT call it on resources
  975. that are already in the filesystem.
  976. `tempname` is the current (temporary) name of the file, and `filename`
  977. is the name it will be renamed to by the caller after this routine
  978. returns.
  979. """
  980. if os.name == 'posix':
  981. # Make the resource executable
  982. mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
  983. os.chmod(tempname, mode)
  984. def set_extraction_path(self, path):
  985. """Set the base path where resources will be extracted to, if needed.
  986. If you do not call this routine before any extractions take place, the
  987. path defaults to the return value of ``get_default_cache()``. (Which
  988. is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  989. platform-specific fallbacks. See that routine's documentation for more
  990. details.)
  991. Resources are extracted to subdirectories of this path based upon
  992. information given by the ``IResourceProvider``. You may set this to a
  993. temporary directory, but then you must call ``cleanup_resources()`` to
  994. delete the extracted files when done. There is no guarantee that
  995. ``cleanup_resources()`` will be able to remove all extracted files.
  996. (Note: you may not change the extraction path for a given resource
  997. manager once resources have been extracted, unless you first call
  998. ``cleanup_resources()``.)
  999. """
  1000. if self.cached_files:
  1001. raise ValueError(
  1002. "Can't change extraction path, files already extracted"
  1003. )
  1004. self.extraction_path = path
  1005. def cleanup_resources(self, force=False):
  1006. """
  1007. Delete all extracted resource files and directories, returning a list
  1008. of the file and directory names that could not be successfully removed.
  1009. This function does not have any concurrency protection, so it should
  1010. generally only be called when the extraction path is a temporary
  1011. directory exclusive to a single process. This method is not
  1012. automatically called; you must call it explicitly or register it as an
  1013. ``atexit`` function if you wish to ensure cleanup of a temporary
  1014. directory used for extractions.
  1015. """
  1016. # XXX
  1017. def get_default_cache():
  1018. """
  1019. Return the ``PYTHON_EGG_CACHE`` environment variable
  1020. or a platform-relevant user cache dir for an app
  1021. named "Python-Eggs".
  1022. """
  1023. return (
  1024. os.environ.get('PYTHON_EGG_CACHE')
  1025. or appdirs.user_cache_dir(appname='Python-Eggs')
  1026. )
  1027. def safe_name(name):
  1028. """Convert an arbitrary string to a standard distribution name
  1029. Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  1030. """
  1031. return re.sub('[^A-Za-z0-9.]+', '-', name)
  1032. def safe_version(version):
  1033. """
  1034. Convert an arbitrary string to a standard version string
  1035. """
  1036. try:
  1037. # normalize the version
  1038. return str(packaging.version.Version(version))
  1039. except packaging.version.InvalidVersion:
  1040. version = version.replace(' ', '.')
  1041. return re.sub('[^A-Za-z0-9.]+', '-', version)
  1042. def safe_extra(extra):
  1043. """Convert an arbitrary string to a standard 'extra' name
  1044. Any runs of non-alphanumeric characters are replaced with a single '_',
  1045. and the result is always lowercased.
  1046. """
  1047. return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
  1048. def to_filename(name):
  1049. """Convert a project or version name to its filename-escaped form
  1050. Any '-' characters are currently replaced with '_'.
  1051. """
  1052. return name.replace('-', '_')
  1053. def invalid_marker(text):
  1054. """
  1055. Validate text as a PEP 508 environment marker; return an exception
  1056. if invalid or False otherwise.
  1057. """
  1058. try:
  1059. evaluate_marker(text)
  1060. except SyntaxError as e:
  1061. e.filename = None
  1062. e.lineno = None
  1063. return e
  1064. return False
  1065. def evaluate_marker(text, extra=None):
  1066. """
  1067. Evaluate a PEP 508 environment marker.
  1068. Return a boolean indicating the marker result in this environment.
  1069. Raise SyntaxError if marker is invalid.
  1070. This implementation uses the 'pyparsing' module.
  1071. """
  1072. try:
  1073. marker = packaging.markers.Marker(text)
  1074. return marker.evaluate()
  1075. except packaging.markers.InvalidMarker as e:
  1076. raise SyntaxError(e) from e
  1077. class NullProvider:
  1078. """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
  1079. egg_name = None
  1080. egg_info = None
  1081. loader = None
  1082. def __init__(self, module):
  1083. self.loader = getattr(module, '__loader__', None)
  1084. self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  1085. def get_resource_filename(self, manager, resource_name):
  1086. return self._fn(self.module_path, resource_name)
  1087. def get_resource_stream(self, manager, resource_name):
  1088. return io.BytesIO(self.get_resource_string(manager, resource_name))
  1089. def get_resource_string(self, manager, resource_name):
  1090. return self._get(self._fn(self.module_path, resource_name))
  1091. def has_resource(self, resource_name):
  1092. return self._has(self._fn(self.module_path, resource_name))
  1093. def _get_metadata_path(self, name):
  1094. return self._fn(self.egg_info, name)
  1095. def has_metadata(self, name):
  1096. if not self.egg_info:
  1097. return self.egg_info
  1098. path = self._get_metadata_path(name)
  1099. return self._has(path)
  1100. def get_metadata(self, name):
  1101. if not self.egg_info:
  1102. return ""
  1103. path = self._get_metadata_path(name)
  1104. value = self._get(path)
  1105. try:
  1106. return value.decode('utf-8')
  1107. except UnicodeDecodeError as exc:
  1108. # Include the path in the error message to simplify
  1109. # troubleshooting, and without changing the exception type.
  1110. exc.reason += ' in {} file at path: {}'.format(name, path)
  1111. raise
  1112. def get_metadata_lines(self, name):
  1113. return yield_lines(self.get_metadata(name))
  1114. def resource_isdir(self, resource_name):
  1115. return self._isdir(self._fn(self.module_path, resource_name))
  1116. def metadata_isdir(self, name):
  1117. return self.egg_info and self._isdir(self._fn(self.egg_info, name))
  1118. def resource_listdir(self, resource_name):
  1119. return self._listdir(self._fn(self.module_path, resource_name))
  1120. def metadata_listdir(self, name):
  1121. if self.egg_info:
  1122. return self._listdir(self._fn(self.egg_info, name))
  1123. return []
  1124. def run_script(self, script_name, namespace):
  1125. script = 'scripts/' + script_name
  1126. if not self.has_metadata(script):
  1127. raise ResolutionError(
  1128. "Script {script!r} not found in metadata at {self.egg_info!r}"
  1129. .format(**locals()),
  1130. )
  1131. script_text = self.get_metadata(script).replace('\r\n', '\n')
  1132. script_text = script_text.replace('\r', '\n')
  1133. script_filename = self._fn(self.egg_info, script)
  1134. namespace['__file__'] = script_filename
  1135. if os.path.exists(script_filename):
  1136. with open(script_filename) as fid:
  1137. source = fid.read()
  1138. code = compile(source, script_filename, 'exec')
  1139. exec(code, namespace, namespace)
  1140. else:
  1141. from linecache import cache
  1142. cache[script_filename] = (
  1143. len(script_text), 0, script_text.split('\n'), script_filename
  1144. )
  1145. script_code = compile(script_text, script_filename, 'exec')
  1146. exec(script_code, namespace, namespace)
  1147. def _has(self, path):
  1148. raise NotImplementedError(
  1149. "Can't perform this operation for unregistered loader type"
  1150. )
  1151. def _isdir(self, path):
  1152. raise NotImplementedError(
  1153. "Can't perform this operation for unregistered loader type"
  1154. )
  1155. def _listdir(self, path):
  1156. raise NotImplementedError(
  1157. "Can't perform this operation for unregistered loader type"
  1158. )
  1159. def _fn(self, base, resource_name):
  1160. self._validate_resource_path(resource_name)
  1161. if resource_name:
  1162. return os.path.join(base, *resource_name.split('/'))
  1163. return base
  1164. @staticmethod
  1165. def _validate_resource_path(path):
  1166. """
  1167. Validate the resource paths according to the docs.
  1168. https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access
  1169. >>> warned = getfixture('recwarn')
  1170. >>> warnings.simplefilter('always')
  1171. >>> vrp = NullProvider._validate_resource_path
  1172. >>> vrp('foo/bar.txt')
  1173. >>> bool(warned)
  1174. False
  1175. >>> vrp('../foo/bar.txt')
  1176. >>> bool(warned)
  1177. True
  1178. >>> warned.clear()
  1179. >>> vrp('/foo/bar.txt')
  1180. >>> bool(warned)
  1181. True
  1182. >>> vrp('foo/../../bar.txt')
  1183. >>> bool(warned)
  1184. True
  1185. >>> warned.clear()
  1186. >>> vrp('foo/f../bar.txt')
  1187. >>> bool(warned)
  1188. False
  1189. Windows path separators are straight-up disallowed.
  1190. >>> vrp(r'\\foo/bar.txt')
  1191. Traceback (most recent call last):
  1192. ...
  1193. ValueError: Use of .. or absolute path in a resource path \
  1194. is not allowed.
  1195. >>> vrp(r'C:\\foo/bar.txt')
  1196. Traceback (most recent call last):
  1197. ...
  1198. ValueError: Use of .. or absolute path in a resource path \
  1199. is not allowed.
  1200. Blank values are allowed
  1201. >>> vrp('')
  1202. >>> bool(warned)
  1203. False
  1204. Non-string values are not.
  1205. >>> vrp(None)
  1206. Traceback (most recent call last):
  1207. ...
  1208. AttributeError: ...
  1209. """
  1210. invalid = (
  1211. os.path.pardir in path.split(posixpath.sep) or
  1212. posixpath.isabs(path) or
  1213. ntpath.isabs(path)
  1214. )
  1215. if not invalid:
  1216. return
  1217. msg = "Use of .. or absolute path in a resource path is not allowed."
  1218. # Aggressively disallow Windows absolute paths
  1219. if ntpath.isabs(path) and not posixpath.isabs(path):
  1220. raise ValueError(msg)
  1221. # for compatibility, warn; in future
  1222. # raise ValueError(msg)
  1223. warnings.warn(
  1224. msg[:-1] + " and will raise exceptions in a future release.",
  1225. DeprecationWarning,
  1226. stacklevel=4,
  1227. )
  1228. def _get(self, path):
  1229. if hasattr(self.loader, 'get_data'):
  1230. return self.loader.get_data(path)
  1231. raise NotImplementedError(
  1232. "Can't perform this operation for loaders without 'get_data()'"
  1233. )
  1234. register_loader_type(object, NullProvider)
  1235. def _parents(path):
  1236. """
  1237. yield all parents of path including path
  1238. """
  1239. last = None
  1240. while path != last:
  1241. yield path
  1242. last = path
  1243. path, _ = os.path.split(path)
  1244. class EggProvider(NullProvider):
  1245. """Provider based on a virtual filesystem"""
  1246. def __init__(self, module):
  1247. NullProvider.__init__(self, module)
  1248. self._setup_prefix()
  1249. def _setup_prefix(self):
  1250. # Assume that metadata may be nested inside a "basket"
  1251. # of multiple eggs and use module_path instead of .archive.
  1252. eggs = filter(_is_egg_path, _parents(self.module_path))
  1253. egg = next(eggs, None)
  1254. egg and self._set_egg(egg)
  1255. def _set_egg(self, path):
  1256. self.egg_name = os.path.basename(path)
  1257. self.egg_info = os.path.join(path, 'EGG-INFO')
  1258. self.egg_root = path
  1259. class DefaultProvider(EggProvider):
  1260. """Provides access to package resources in the filesystem"""
  1261. def _has(self, path):
  1262. return os.path.exists(path)
  1263. def _isdir(self, path):
  1264. return os.path.isdir(path)
  1265. def _listdir(self, path):
  1266. return os.listdir(path)
  1267. def get_resource_stream(self, manager, resource_name):
  1268. return open(self._fn(self.module_path, resource_name), 'rb')
  1269. def _get(self, path):
  1270. with open(path, 'rb') as stream:
  1271. return stream.read()
  1272. @classmethod
  1273. def _register(cls):
  1274. loader_names = 'SourceFileLoader', 'SourcelessFileLoader',
  1275. for name in loader_names:
  1276. loader_cls = getattr(importlib_machinery, name, type(None))
  1277. register_loader_type(loader_cls, cls)
  1278. DefaultProvider._register()
  1279. class EmptyProvider(NullProvider):
  1280. """Provider that returns nothing for all requests"""
  1281. module_path = None
  1282. _isdir = _has = lambda self, path: False
  1283. def _get(self, path):
  1284. return ''
  1285. def _listdir(self, path):
  1286. return []
  1287. def __init__(self):
  1288. pass
  1289. empty_provider = EmptyProvider()
  1290. class ZipManifests(dict):
  1291. """
  1292. zip manifest builder
  1293. """
  1294. @classmethod
  1295. def build(cls, path):
  1296. """
  1297. Build a dictionary similar to the zipimport directory
  1298. caches, except instead of tuples, store ZipInfo objects.
  1299. Use a platform-specific path separator (os.sep) for the path keys
  1300. for compatibility with pypy on Windows.
  1301. """
  1302. with zipfile.ZipFile(path) as zfile:
  1303. items = (
  1304. (
  1305. name.replace('/', os.sep),
  1306. zfile.getinfo(name),
  1307. )
  1308. for name in zfile.namelist()
  1309. )
  1310. return dict(items)
  1311. load = build
  1312. class MemoizedZipManifests(ZipManifests):
  1313. """
  1314. Memoized zipfile manifests.
  1315. """
  1316. manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')
  1317. def load(self, path):
  1318. """
  1319. Load a manifest at path or return a suitable manifest already loaded.
  1320. """
  1321. path = os.path.normpath(path)
  1322. mtime = os.stat(path).st_mtime
  1323. if path not in self or self[path].mtime != mtime:
  1324. manifest = self.build(path)
  1325. self[path] = self.manifest_mod(manifest, mtime)
  1326. return self[path].manifest
  1327. class ZipProvider(EggProvider):
  1328. """Resource support for zips and eggs"""
  1329. eagers = None
  1330. _zip_manifests = MemoizedZipManifests()
  1331. def __init__(self, module):
  1332. EggProvider.__init__(self, module)
  1333. self.zip_pre = self.loader.archive + os.sep
  1334. def _zipinfo_name(self, fspath):
  1335. # Convert a virtual filename (full path to file) into a zipfile subpath
  1336. # usable with the zipimport directory cache for our target archive
  1337. fspath = fspath.rstrip(os.sep)
  1338. if fspath == self.loader.archive:
  1339. return ''
  1340. if fspath.startswith(self.zip_pre):
  1341. return fspath[len(self.zip_pre):]
  1342. raise AssertionError(
  1343. "%s is not a subpath of %s" % (fspath, self.zip_pre)
  1344. )
  1345. def _parts(self, zip_path):
  1346. # Convert a zipfile subpath into an egg-relative path part list.
  1347. # pseudo-fs path
  1348. fspath = self.zip_pre + zip_path
  1349. if fspath.startswith(self.egg_root + os.sep):
  1350. return fspath[len(self.egg_root) + 1:].split(os.sep)
  1351. raise AssertionError(
  1352. "%s is not a subpath of %s" % (fspath, self.egg_root)
  1353. )
  1354. @property
  1355. def zipinfo(self):
  1356. return self._zip_manifests.load(self.loader.archive)
  1357. def get_resource_filename(self, manager, resource_name):
  1358. if not self.egg_name:
  1359. raise NotImplementedError(
  1360. "resource_filename() only supported for .egg, not .zip"
  1361. )
  1362. # no need to lock for extraction, since we use temp names
  1363. zip_path = self._resource_to_zip(resource_name)
  1364. eagers = self._get_eager_resources()
  1365. if '/'.join(self._parts(zip_path)) in eagers:
  1366. for name in eagers:
  1367. self._extract_resource(manager, self._eager_to_zip(name))
  1368. return self._extract_resource(manager, zip_path)
  1369. @staticmethod
  1370. def _get_date_and_size(zip_stat):
  1371. size = zip_stat.file_size
  1372. # ymdhms+wday, yday, dst
  1373. date_time = zip_stat.date_time + (0, 0, -1)
  1374. # 1980 offset already done
  1375. timestamp = time.mktime(date_time)
  1376. return timestamp, size
  1377. # FIXME: 'ZipProvider._extract_resource' is too complex (12)
  1378. def _extract_resource(self, manager, zip_path): # noqa: C901
  1379. if zip_path in self._index():
  1380. for name in self._index()[zip_path]:
  1381. last = self._extract_resource(
  1382. manager, os.path.join(zip_path, name)
  1383. )
  1384. # return the extracted directory name
  1385. return os.path.dirname(last)
  1386. timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
  1387. if not WRITE_SUPPORT:
  1388. raise IOError('"os.rename" and "os.unlink" are not supported '
  1389. 'on this platform')
  1390. try:
  1391. real_path = manager.get_cache_path(
  1392. self.egg_name, self._parts(zip_path)
  1393. )
  1394. if self._is_current(real_path, zip_path):
  1395. return real_path
  1396. outf, tmpnam = _mkstemp(
  1397. ".$extract",
  1398. dir=os.path.dirname(real_path),
  1399. )
  1400. os.write(outf, self.loader.get_data(zip_path))
  1401. os.close(outf)
  1402. utime(tmpnam, (timestamp, timestamp))
  1403. manager.postprocess(tmpnam, real_path)
  1404. try:
  1405. rename(tmpnam, real_path)
  1406. except os.error:
  1407. if os.path.isfile(real_path):
  1408. if self._is_current(real_path, zip_path):
  1409. # the file became current since it was checked above,
  1410. # so proceed.
  1411. return real_path
  1412. # Windows, del old file and retry
  1413. elif os.name == 'nt':
  1414. unlink(real_path)
  1415. rename(tmpnam, real_path)
  1416. return real_path
  1417. raise
  1418. except os.error:
  1419. # report a user-friendly error
  1420. manager.extraction_error()
  1421. return real_path
  1422. def _is_current(self, file_path, zip_path):
  1423. """
  1424. Return True if the file_path is current for this zip_path
  1425. """
  1426. timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
  1427. if not os.path.isfile(file_path):
  1428. return False
  1429. stat = os.stat(file_path)
  1430. if stat.st_size != size or stat.st_mtime != timestamp:
  1431. return False
  1432. # check that the contents match
  1433. zip_contents = self.loader.get_data(zip_path)
  1434. with open(file_path, 'rb') as f:
  1435. file_contents = f.read()
  1436. return zip_contents == file_contents
  1437. def _get_eager_resources(self):
  1438. if self.eagers is None:
  1439. eagers = []
  1440. for name in ('native_libs.txt', 'eager_resources.txt'):
  1441. if self.has_metadata(name):
  1442. eagers.extend(self.get_metadata_lines(name))
  1443. self.eagers = eagers
  1444. return self.eagers
  1445. def _index(self):
  1446. try:
  1447. return self._dirindex
  1448. except AttributeError:
  1449. ind = {}
  1450. for path in self.zipinfo:
  1451. parts = path.split(os.sep)
  1452. while parts:
  1453. parent = os.sep.join(parts[:-1])
  1454. if parent in ind:
  1455. ind[parent].append(parts[-1])
  1456. break
  1457. else:
  1458. ind[parent] = [parts.pop()]
  1459. self._dirindex = ind
  1460. return ind
  1461. def _has(self, fspath):
  1462. zip_path = self._zipinfo_name(fspath)
  1463. return zip_path in self.zipinfo or zip_path in self._index()
  1464. def _isdir(self, fspath):
  1465. return self._zipinfo_name(fspath) in self._index()
  1466. def _listdir(self, fspath):
  1467. return list(self._index().get(self._zipinfo_name(fspath), ()))
  1468. def _eager_to_zip(self, resource_name):
  1469. return self._zipinfo_name(self._fn(self.egg_root, resource_name))
  1470. def _resource_to_zip(self, resource_name):
  1471. return self._zipinfo_name(self._fn(self.module_path, resource_name))
  1472. register_loader_type(zipimport.zipimporter, ZipProvider)
  1473. class FileMetadata(EmptyProvider):
  1474. """Metadata handler for standalone PKG-INFO files
  1475. Usage::
  1476. metadata = FileMetadata("/path/to/PKG-INFO")
  1477. This provider rejects all data and metadata requests except for PKG-INFO,
  1478. which is treated as existing, and will be the contents of the file at
  1479. the provided location.
  1480. """
  1481. def __init__(self, path):
  1482. self.path = path
  1483. def _get_metadata_path(self, name):
  1484. return self.path
  1485. def has_metadata(self, name):
  1486. return name == 'PKG-INFO' and os.path.isfile(self.path)
  1487. def get_metadata(self, name):
  1488. if name != 'PKG-INFO':
  1489. raise KeyError("No metadata except PKG-INFO is available")
  1490. with io.open(self.path, encoding='utf-8', errors="replace") as f:
  1491. metadata = f.read()
  1492. self._warn_on_replacement(metadata)
  1493. return metadata
  1494. def _warn_on_replacement(self, metadata):
  1495. replacement_char = '�'
  1496. if replacement_char in metadata:
  1497. tmpl = "{self.path} could not be properly decoded in UTF-8"
  1498. msg = tmpl.format(**locals())
  1499. warnings.warn(msg)
  1500. def get_metadata_lines(self, name):
  1501. return yield_lines(self.get_metadata(name))
  1502. class PathMetadata(DefaultProvider):
  1503. """Metadata provider for egg directories
  1504. Usage::
  1505. # Development eggs:
  1506. egg_info = "/path/to/PackageName.egg-info"
  1507. base_dir = os.path.dirname(egg_info)
  1508. metadata = PathMetadata(base_dir, egg_info)
  1509. dist_name = os.path.splitext(os.path.basename(egg_info))[0]
  1510. dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
  1511. # Unpacked egg directories:
  1512. egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
  1513. metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
  1514. dist = Distribution.from_filename(egg_path, metadata=metadata)
  1515. """
  1516. def __init__(self, path, egg_info):
  1517. self.module_path = path
  1518. self.egg_info = egg_info
  1519. class EggMetadata(ZipProvider):
  1520. """Metadata provider for .egg files"""
  1521. def __init__(self, importer):
  1522. """Create a metadata provider from a zipimporter"""
  1523. self.zip_pre = importer.archive + os.sep
  1524. self.loader = importer
  1525. if importer.prefix:
  1526. self.module_path = os.path.join(importer.archive, importer.prefix)
  1527. else:
  1528. self.module_path = importer.archive
  1529. self._setup_prefix()
  1530. _declare_state('dict', _distribution_finders={})
  1531. def register_finder(importer_type, distribution_finder):
  1532. """Register `distribution_finder` to find distributions in sys.path items
  1533. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1534. handler), and `distribution_finder` is a callable that, passed a path
  1535. item and the importer instance, yields ``Distribution`` instances found on
  1536. that path item. See ``pkg_resources.find_on_path`` for an example."""
  1537. _distribution_finders[importer_type] = distribution_finder
  1538. def find_distributions(path_item, only=False):
  1539. """Yield distributions accessible via `path_item`"""
  1540. importer = get_importer(path_item)
  1541. finder = _find_adapter(_distribution_finders, importer)
  1542. return finder(importer, path_item, only)
  1543. def find_eggs_in_zip(importer, path_item, only=False):
  1544. """
  1545. Find eggs in zip files; possibly multiple nested eggs.
  1546. """
  1547. if importer.archive.endswith('.whl'):
  1548. # wheels are not supported with this finder
  1549. # they don't have PKG-INFO metadata, and won't ever contain eggs
  1550. return
  1551. metadata = EggMetadata(importer)
  1552. if metadata.has_metadata('PKG-INFO'):
  1553. yield Distribution.from_filename(path_item, metadata=metadata)
  1554. if only:
  1555. # don't yield nested distros
  1556. return
  1557. for subitem in metadata.resource_listdir(''):
  1558. if _is_egg_path(subitem):
  1559. subpath = os.path.join(path_item, subitem)
  1560. dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
  1561. for dist in dists:
  1562. yield dist
  1563. elif subitem.lower().endswith(('.dist-info', '.egg-info')):
  1564. subpath = os.path.join(path_item, subitem)
  1565. submeta = EggMetadata(zipimport.zipimporter(subpath))
  1566. submeta.egg_info = subpath
  1567. yield Distribution.from_location(path_item, subitem, submeta)
  1568. register_finder(zipimport.zipimporter, find_eggs_in_zip)
  1569. def find_nothing(importer, path_item, only=False):
  1570. return ()
  1571. register_finder(object, find_nothing)
  1572. def _by_version_descending(names):
  1573. """
  1574. Given a list of filenames, return them in descending order
  1575. by version number.
  1576. >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
  1577. >>> _by_version_descending(names)
  1578. ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
  1579. >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
  1580. >>> _by_version_descending(names)
  1581. ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
  1582. >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
  1583. >>> _by_version_descending(names)
  1584. ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
  1585. """
  1586. def _by_version(name):
  1587. """
  1588. Parse each component of the filename
  1589. """
  1590. name, ext = os.path.splitext(name)
  1591. parts = itertools.chain(name.split('-'), [ext])
  1592. return [packaging.version.parse(part) for part in parts]
  1593. return sorted(names, key=_by_version, reverse=True)
  1594. def find_on_path(importer, path_item, only=False):
  1595. """Yield distributions accessible on a sys.path directory"""
  1596. path_item = _normalize_cached(path_item)
  1597. if _is_unpacked_egg(path_item):
  1598. yield Distribution.from_filename(
  1599. path_item, metadata=PathMetadata(
  1600. path_item, os.path.join(path_item, 'EGG-INFO')
  1601. )
  1602. )
  1603. return
  1604. entries = (
  1605. os.path.join(path_item, child)
  1606. for child in safe_listdir(path_item)
  1607. )
  1608. # for performance, before sorting by version,
  1609. # screen entries for only those that will yield
  1610. # distributions
  1611. filtered = (
  1612. entry
  1613. for entry in entries
  1614. if dist_factory(path_item, entry, only)
  1615. )
  1616. # scan for .egg and .egg-info in directory
  1617. path_item_entries = _by_version_descending(filtered)
  1618. for entry in path_item_entries:
  1619. fullpath = os.path.join(path_item, entry)
  1620. factory = dist_factory(path_item, entry, only)
  1621. for dist in factory(fullpath):
  1622. yield dist
  1623. def dist_factory(path_item, entry, only):
  1624. """Return a dist_factory for the given entry."""
  1625. lower = entry.lower()
  1626. is_egg_info = lower.endswith('.egg-info')
  1627. is_dist_info = (
  1628. lower.endswith('.dist-info') and
  1629. os.path.isdir(os.path.join(path_item, entry))
  1630. )
  1631. is_meta = is_egg_info or is_dist_info
  1632. return (
  1633. distributions_from_metadata
  1634. if is_meta else
  1635. find_distributions
  1636. if not only and _is_egg_path(entry) else
  1637. resolve_egg_link
  1638. if not only and lower.endswith('.egg-link') else
  1639. NoDists()
  1640. )
  1641. class NoDists:
  1642. """
  1643. >>> bool(NoDists())
  1644. False
  1645. >>> list(NoDists()('anything'))
  1646. []
  1647. """
  1648. def __bool__(self):
  1649. return False
  1650. def __call__(self, fullpath):
  1651. return iter(())
  1652. def safe_listdir(path):
  1653. """
  1654. Attempt to list contents of path, but suppress some exceptions.
  1655. """
  1656. try:
  1657. return os.listdir(path)
  1658. except (PermissionError, NotADirectoryError):
  1659. pass
  1660. except OSError as e:
  1661. # Ignore the directory if does not exist, not a directory or
  1662. # permission denied
  1663. if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):
  1664. raise
  1665. return ()
  1666. def distributions_from_metadata(path):
  1667. root = os.path.dirname(path)
  1668. if os.path.isdir(path):
  1669. if len(os.listdir(path)) == 0:
  1670. # empty metadata dir; skip
  1671. return
  1672. metadata = PathMetadata(root, path)
  1673. else:
  1674. metadata = FileMetadata(path)
  1675. entry = os.path.basename(path)
  1676. yield Distribution.from_location(
  1677. root, entry, metadata, precedence=DEVELOP_DIST,
  1678. )
  1679. def non_empty_lines(path):
  1680. """
  1681. Yield non-empty lines from file at path
  1682. """
  1683. with open(path) as f:
  1684. for line in f:
  1685. line = line.strip()
  1686. if line:
  1687. yield line
  1688. def resolve_egg_link(path):
  1689. """
  1690. Given a path to an .egg-link, resolve distributions
  1691. present in the referenced path.
  1692. """
  1693. referenced_paths = non_empty_lines(path)
  1694. resolved_paths = (
  1695. os.path.join(os.path.dirname(path), ref)
  1696. for ref in referenced_paths
  1697. )
  1698. dist_groups = map(find_distributions, resolved_paths)
  1699. return next(dist_groups, ())
  1700. register_finder(pkgutil.ImpImporter, find_on_path)
  1701. if hasattr(importlib_machinery, 'FileFinder'):
  1702. register_finder(importlib_machinery.FileFinder, find_on_path)
  1703. _declare_state('dict', _namespace_handlers={})
  1704. _declare_state('dict', _namespace_packages={})
  1705. def register_namespace_handler(importer_type, namespace_handler):
  1706. """Register `namespace_handler` to declare namespace packages
  1707. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1708. handler), and `namespace_handler` is a callable like this::
  1709. def namespace_handler(importer, path_entry, moduleName, module):
  1710. # return a path_entry to use for child packages
  1711. Namespace handlers are only called if the importer object has already
  1712. agreed that it can handle the relevant path item, and they should only
  1713. return a subpath if the module __path__ does not already contain an
  1714. equivalent subpath. For an example namespace handler, see
  1715. ``pkg_resources.file_ns_handler``.
  1716. """
  1717. _namespace_handlers[importer_type] = namespace_handler
  1718. def _handle_ns(packageName, path_item):
  1719. """Ensure that named package includes a subpath of path_item (if needed)"""
  1720. importer = get_importer(path_item)
  1721. if importer is None:
  1722. return None
  1723. # use find_spec (PEP 451) and fall-back to find_module (PEP 302)
  1724. try:
  1725. loader = importer.find_spec(packageName).loader
  1726. except AttributeError:
  1727. # capture warnings due to #1111
  1728. with warnings.catch_warnings():
  1729. warnings.simplefilter("ignore")
  1730. loader = importer.find_module(packageName)
  1731. if loader is None:
  1732. return None
  1733. module = sys.modules.get(packageName)
  1734. if module is None:
  1735. module = sys.modules[packageName] = types.ModuleType(packageName)
  1736. module.__path__ = []
  1737. _set_parent_ns(packageName)
  1738. elif not hasattr(module, '__path__'):
  1739. raise TypeError("Not a package:", packageName)
  1740. handler = _find_adapter(_namespace_handlers, importer)
  1741. subpath = handler(importer, path_item, packageName, module)
  1742. if subpath is not None:
  1743. path = module.__path__
  1744. path.append(subpath)
  1745. importlib.import_module(packageName)
  1746. _rebuild_mod_path(path, packageName, module)
  1747. return subpath
  1748. def _rebuild_mod_path(orig_path, package_name, module):
  1749. """
  1750. Rebuild module.__path__ ensuring that all entries are ordered
  1751. corresponding to their sys.path order
  1752. """
  1753. sys_path = [_normalize_cached(p) for p in sys.path]
  1754. def safe_sys_path_index(entry):
  1755. """
  1756. Workaround for #520 and #513.
  1757. """
  1758. try:
  1759. return sys_path.index(entry)
  1760. except ValueError:
  1761. return float('inf')
  1762. def position_in_sys_path(path):
  1763. """
  1764. Return the ordinal of the path based on its position in sys.path
  1765. """
  1766. path_parts = path.split(os.sep)
  1767. module_parts = package_name.count('.') + 1
  1768. parts = path_parts[:-module_parts]
  1769. return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
  1770. new_path = sorted(orig_path, key=position_in_sys_path)
  1771. new_path = [_normalize_cached(p) for p in new_path]
  1772. if isinstance(module.__path__, list):
  1773. module.__path__[:] = new_path
  1774. else:
  1775. module.__path__ = new_path
  1776. def declare_namespace(packageName):
  1777. """Declare that package 'packageName' is a namespace package"""
  1778. _imp.acquire_lock()
  1779. try:
  1780. if packageName in _namespace_packages:
  1781. return
  1782. path = sys.path
  1783. parent, _, _ = packageName.rpartition('.')
  1784. if parent:
  1785. declare_namespace(parent)
  1786. if parent not in _namespace_packages:
  1787. __import__(parent)
  1788. try:
  1789. path = sys.modules[parent].__path__
  1790. except AttributeError as e:
  1791. raise TypeError("Not a package:", parent) from e
  1792. # Track what packages are namespaces, so when new path items are added,
  1793. # they can be updated
  1794. _namespace_packages.setdefault(parent or None, []).append(packageName)
  1795. _namespace_packages.setdefault(packageName, [])
  1796. for path_item in path:
  1797. # Ensure all the parent's path items are reflected in the child,
  1798. # if they apply
  1799. _handle_ns(packageName, path_item)
  1800. finally:
  1801. _imp.release_lock()
  1802. def fixup_namespace_packages(path_item, parent=None):
  1803. """Ensure that previously-declared namespace packages include path_item"""
  1804. _imp.acquire_lock()
  1805. try:
  1806. for package in _namespace_packages.get(parent, ()):
  1807. subpath = _handle_ns(package, path_item)
  1808. if subpath:
  1809. fixup_namespace_packages(subpath, package)
  1810. finally:
  1811. _imp.release_lock()
  1812. def file_ns_handler(importer, path_item, packageName, module):
  1813. """Compute an ns-package subpath for a filesystem or zipfile importer"""
  1814. subpath = os.path.join(path_item, packageName.split('.')[-1])
  1815. normalized = _normalize_cached(subpath)
  1816. for item in module.__path__:
  1817. if _normalize_cached(item) == normalized:
  1818. break
  1819. else:
  1820. # Only return the path if it's not already there
  1821. return subpath
  1822. register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
  1823. register_namespace_handler(zipimport.zipimporter, file_ns_handler)
  1824. if hasattr(importlib_machinery, 'FileFinder'):
  1825. register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)
  1826. def null_ns_handler(importer, path_item, packageName, module):
  1827. return None
  1828. register_namespace_handler(object, null_ns_handler)
  1829. def normalize_path(filename):
  1830. """Normalize a file/dir name for comparison purposes"""
  1831. return os.path.normcase(os.path.realpath(os.path.normpath(
  1832. _cygwin_patch(filename))))
  1833. def _cygwin_patch(filename): # pragma: nocover
  1834. """
  1835. Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
  1836. symlink components. Using
  1837. os.path.abspath() works around this limitation. A fix in os.getcwd()
  1838. would probably better, in Cygwin even more so, except
  1839. that this seems to be by design...
  1840. """
  1841. return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
  1842. def _normalize_cached(filename, _cache={}):
  1843. try:
  1844. return _cache[filename]
  1845. except KeyError:
  1846. _cache[filename] = result = normalize_path(filename)
  1847. return result
  1848. def _is_egg_path(path):
  1849. """
  1850. Determine if given path appears to be an egg.
  1851. """
  1852. return _is_zip_egg(path) or _is_unpacked_egg(path)
  1853. def _is_zip_egg(path):
  1854. return (
  1855. path.lower().endswith('.egg') and
  1856. os.path.isfile(path) and
  1857. zipfile.is_zipfile(path)
  1858. )
  1859. def _is_unpacked_egg(path):
  1860. """
  1861. Determine if given path appears to be an unpacked egg.
  1862. """
  1863. return (
  1864. path.lower().endswith('.egg') and
  1865. os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
  1866. )
  1867. def _set_parent_ns(packageName):
  1868. parts = packageName.split('.')
  1869. name = parts.pop()
  1870. if parts:
  1871. parent = '.'.join(parts)
  1872. setattr(sys.modules[parent], name, sys.modules[packageName])
  1873. def yield_lines(strs):
  1874. """Yield non-empty/non-comment lines of a string or sequence"""
  1875. if isinstance(strs, str):
  1876. for s in strs.splitlines():
  1877. s = s.strip()
  1878. # skip blank lines/comments
  1879. if s and not s.startswith('#'):
  1880. yield s
  1881. else:
  1882. for ss in strs:
  1883. for s in yield_lines(ss):
  1884. yield s
  1885. MODULE = re.compile(r"\w+(\.\w+)*$").match
  1886. EGG_NAME = re.compile(
  1887. r"""
  1888. (?P<name>[^-]+) (
  1889. -(?P<ver>[^-]+) (
  1890. -py(?P<pyver>[^-]+) (
  1891. -(?P<plat>.+)
  1892. )?
  1893. )?
  1894. )?
  1895. """,
  1896. re.VERBOSE | re.IGNORECASE,
  1897. ).match
  1898. class EntryPoint:
  1899. """Object representing an advertised importable object"""
  1900. def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
  1901. if not MODULE(module_name):
  1902. raise ValueError("Invalid module name", module_name)
  1903. self.name = name
  1904. self.module_name = module_name
  1905. self.attrs = tuple(attrs)
  1906. self.extras = tuple(extras)
  1907. self.dist = dist
  1908. def __str__(self):
  1909. s = "%s = %s" % (self.name, self.module_name)
  1910. if self.attrs:
  1911. s += ':' + '.'.join(self.attrs)
  1912. if self.extras:
  1913. s += ' [%s]' % ','.join(self.extras)
  1914. return s
  1915. def __repr__(self):
  1916. return "EntryPoint.parse(%r)" % str(self)
  1917. def load(self, require=True, *args, **kwargs):
  1918. """
  1919. Require packages for this EntryPoint, then resolve it.
  1920. """
  1921. if not require or args or kwargs:
  1922. warnings.warn(
  1923. "Parameters to load are deprecated. Call .resolve and "
  1924. ".require separately.",
  1925. PkgResourcesDeprecationWarning,
  1926. stacklevel=2,
  1927. )
  1928. if require:
  1929. self.require(*args, **kwargs)
  1930. return self.resolve()
  1931. def resolve(self):
  1932. """
  1933. Resolve the entry point from its module and attrs.
  1934. """
  1935. module = __import__(self.module_name, fromlist=['__name__'], level=0)
  1936. try:
  1937. return functools.reduce(getattr, self.attrs, module)
  1938. except AttributeError as exc:
  1939. raise ImportError(str(exc)) from exc
  1940. def require(self, env=None, installer=None):
  1941. if self.extras and not self.dist:
  1942. raise UnknownExtra("Can't require() without a distribution", self)
  1943. # Get the requirements for this entry point with all its extras and
  1944. # then resolve them. We have to pass `extras` along when resolving so
  1945. # that the working set knows what extras we want. Otherwise, for
  1946. # dist-info distributions, the working set will assume that the
  1947. # requirements for that extra are purely optional and skip over them.
  1948. reqs = self.dist.requires(self.extras)
  1949. items = working_set.resolve(reqs, env, installer, extras=self.extras)
  1950. list(map(working_set.add, items))
  1951. pattern = re.compile(
  1952. r'\s*'
  1953. r'(?P<name>.+?)\s*'
  1954. r'=\s*'
  1955. r'(?P<module>[\w.]+)\s*'
  1956. r'(:\s*(?P<attr>[\w.]+))?\s*'
  1957. r'(?P<extras>\[.*\])?\s*$'
  1958. )
  1959. @classmethod
  1960. def parse(cls, src, dist=None):
  1961. """Parse a single entry point from string `src`
  1962. Entry point syntax follows the form::
  1963. name = some.module:some.attr [extra1, extra2]
  1964. The entry name and module name are required, but the ``:attrs`` and
  1965. ``[extras]`` parts are optional
  1966. """
  1967. m = cls.pattern.match(src)
  1968. if not m:
  1969. msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
  1970. raise ValueError(msg, src)
  1971. res = m.groupdict()
  1972. extras = cls._parse_extras(res['extras'])
  1973. attrs = res['attr'].split('.') if res['attr'] else ()
  1974. return cls(res['name'], res['module'], attrs, extras, dist)
  1975. @classmethod
  1976. def _parse_extras(cls, extras_spec):
  1977. if not extras_spec:
  1978. return ()
  1979. req = Requirement.parse('x' + extras_spec)
  1980. if req.specs:
  1981. raise ValueError()
  1982. return req.extras
  1983. @classmethod
  1984. def parse_group(cls, group, lines, dist=None):
  1985. """Parse an entry point group"""
  1986. if not MODULE(group):
  1987. raise ValueError("Invalid group name", group)
  1988. this = {}
  1989. for line in yield_lines(lines):
  1990. ep = cls.parse(line, dist)
  1991. if ep.name in this:
  1992. raise ValueError("Duplicate entry point", group, ep.name)
  1993. this[ep.name] = ep
  1994. return this
  1995. @classmethod
  1996. def parse_map(cls, data, dist=None):
  1997. """Parse a map of entry point groups"""
  1998. if isinstance(data, dict):
  1999. data = data.items()
  2000. else:
  2001. data = split_sections(data)
  2002. maps = {}
  2003. for group, lines in data:
  2004. if group is None:
  2005. if not lines:
  2006. continue
  2007. raise ValueError("Entry points must be listed in groups")
  2008. group = group.strip()
  2009. if group in maps:
  2010. raise ValueError("Duplicate group name", group)
  2011. maps[group] = cls.parse_group(group, lines, dist)
  2012. return maps
  2013. def _version_from_file(lines):
  2014. """
  2015. Given an iterable of lines from a Metadata file, return
  2016. the value of the Version field, if present, or None otherwise.
  2017. """
  2018. def is_version_line(line):
  2019. return line.lower().startswith('version:')
  2020. version_lines = filter(is_version_line, lines)
  2021. line = next(iter(version_lines), '')
  2022. _, _, value = line.partition(':')
  2023. return safe_version(value.strip()) or None
  2024. class Distribution:
  2025. """Wrap an actual or potential sys.path entry w/metadata"""
  2026. PKG_INFO = 'PKG-INFO'
  2027. def __init__(
  2028. self, location=None, metadata=None, project_name=None,
  2029. version=None, py_version=PY_MAJOR, platform=None,
  2030. precedence=EGG_DIST):
  2031. self.project_name = safe_name(project_name or 'Unknown')
  2032. if version is not None:
  2033. self._version = safe_version(version)
  2034. self.py_version = py_version
  2035. self.platform = platform
  2036. self.location = location
  2037. self.precedence = precedence
  2038. self._provider = metadata or empty_provider
  2039. @classmethod
  2040. def from_location(cls, location, basename, metadata=None, **kw):
  2041. project_name, version, py_version, platform = [None] * 4
  2042. basename, ext = os.path.splitext(basename)
  2043. if ext.lower() in _distributionImpl:
  2044. cls = _distributionImpl[ext.lower()]
  2045. match = EGG_NAME(basename)
  2046. if match:
  2047. project_name, version, py_version, platform = match.group(
  2048. 'name', 'ver', 'pyver', 'plat'
  2049. )
  2050. return cls(
  2051. location, metadata, project_name=project_name, version=version,
  2052. py_version=py_version, platform=platform, **kw
  2053. )._reload_version()
  2054. def _reload_version(self):
  2055. return self
  2056. @property
  2057. def hashcmp(self):
  2058. return (
  2059. self.parsed_version,
  2060. self.precedence,
  2061. self.key,
  2062. self.location,
  2063. self.py_version or '',
  2064. self.platform or '',
  2065. )
  2066. def __hash__(self):
  2067. return hash(self.hashcmp)
  2068. def __lt__(self, other):
  2069. return self.hashcmp < other.hashcmp
  2070. def __le__(self, other):
  2071. return self.hashcmp <= other.hashcmp
  2072. def __gt__(self, other):
  2073. return self.hashcmp > other.hashcmp
  2074. def __ge__(self, other):
  2075. return self.hashcmp >= other.hashcmp
  2076. def __eq__(self, other):
  2077. if not isinstance(other, self.__class__):
  2078. # It's not a Distribution, so they are not equal
  2079. return False
  2080. return self.hashcmp == other.hashcmp
  2081. def __ne__(self, other):
  2082. return not self == other
  2083. # These properties have to be lazy so that we don't have to load any
  2084. # metadata until/unless it's actually needed. (i.e., some distributions
  2085. # may not know their name or version without loading PKG-INFO)
  2086. @property
  2087. def key(self):
  2088. try:
  2089. return self._key
  2090. except AttributeError:
  2091. self._key = key = self.project_name.lower()
  2092. return key
  2093. @property
  2094. def parsed_version(self):
  2095. if not hasattr(self, "_parsed_version"):
  2096. self._parsed_version = parse_version(self.version)
  2097. return self._parsed_version
  2098. def _warn_legacy_version(self):
  2099. LV = packaging.version.LegacyVersion
  2100. is_legacy = isinstance(self._parsed_version, LV)
  2101. if not is_legacy:
  2102. return
  2103. # While an empty version is technically a legacy version and
  2104. # is not a valid PEP 440 version, it's also unlikely to
  2105. # actually come from someone and instead it is more likely that
  2106. # it comes from setuptools attempting to parse a filename and
  2107. # including it in the list. So for that we'll gate this warning
  2108. # on if the version is anything at all or not.
  2109. if not self.version:
  2110. return
  2111. tmpl = textwrap.dedent("""
  2112. '{project_name} ({version})' is being parsed as a legacy,
  2113. non PEP 440,
  2114. version. You may find odd behavior and sort order.
  2115. In particular it will be sorted as less than 0.0. It
  2116. is recommended to migrate to PEP 440 compatible
  2117. versions.
  2118. """).strip().replace('\n', ' ')
  2119. warnings.warn(tmpl.format(**vars(self)), PEP440Warning)
  2120. @property
  2121. def version(self):
  2122. try:
  2123. return self._version
  2124. except AttributeError as e:
  2125. version = self._get_version()
  2126. if version is None:
  2127. path = self._get_metadata_path_for_display(self.PKG_INFO)
  2128. msg = (
  2129. "Missing 'Version:' header and/or {} file at path: {}"
  2130. ).format(self.PKG_INFO, path)
  2131. raise ValueError(msg, self) from e
  2132. return version
  2133. @property
  2134. def _dep_map(self):
  2135. """
  2136. A map of extra to its list of (direct) requirements
  2137. for this distribution, including the null extra.
  2138. """
  2139. try:
  2140. return self.__dep_map
  2141. except AttributeError:
  2142. self.__dep_map = self._filter_extras(self._build_dep_map())
  2143. return self.__dep_map
  2144. @staticmethod
  2145. def _filter_extras(dm):
  2146. """
  2147. Given a mapping of extras to dependencies, strip off
  2148. environment markers and filter out any dependencies
  2149. not matching the markers.
  2150. """
  2151. for extra in list(filter(None, dm)):
  2152. new_extra = extra
  2153. reqs = dm.pop(extra)
  2154. new_extra, _, marker = extra.partition(':')
  2155. fails_marker = marker and (
  2156. invalid_marker(marker)
  2157. or not evaluate_marker(marker)
  2158. )
  2159. if fails_marker:
  2160. reqs = []
  2161. new_extra = safe_extra(new_extra) or None
  2162. dm.setdefault(new_extra, []).extend(reqs)
  2163. return dm
  2164. def _build_dep_map(self):
  2165. dm = {}
  2166. for name in 'requires.txt', 'depends.txt':
  2167. for extra, reqs in split_sections(self._get_metadata(name)):
  2168. dm.setdefault(extra, []).extend(parse_requirements(reqs))
  2169. return dm
  2170. def requires(self, extras=()):
  2171. """List of Requirements needed for this distro if `extras` are used"""
  2172. dm = self._dep_map
  2173. deps = []
  2174. deps.extend(dm.get(None, ()))
  2175. for ext in extras:
  2176. try:
  2177. deps.extend(dm[safe_extra(ext)])
  2178. except KeyError as e:
  2179. raise UnknownExtra(
  2180. "%s has no such extra feature %r" % (self, ext)
  2181. ) from e
  2182. return deps
  2183. def _get_metadata_path_for_display(self, name):
  2184. """
  2185. Return the path to the given metadata file, if available.
  2186. """
  2187. try:
  2188. # We need to access _get_metadata_path() on the provider object
  2189. # directly rather than through this class's __getattr__()
  2190. # since _get_metadata_path() is marked private.
  2191. path = self._provider._get_metadata_path(name)
  2192. # Handle exceptions e.g. in case the distribution's metadata
  2193. # provider doesn't support _get_metadata_path().
  2194. except Exception:
  2195. return '[could not detect]'
  2196. return path
  2197. def _get_metadata(self, name):
  2198. if self.has_metadata(name):
  2199. for line in self.get_metadata_lines(name):
  2200. yield line
  2201. def _get_version(self):
  2202. lines = self._get_metadata(self.PKG_INFO)
  2203. version = _version_from_file(lines)
  2204. return version
  2205. def activate(self, path=None, replace=False):
  2206. """Ensure distribution is importable on `path` (default=sys.path)"""
  2207. if path is None:
  2208. path = sys.path
  2209. self.insert_on(path, replace=replace)
  2210. if path is sys.path:
  2211. fixup_namespace_packages(self.location)
  2212. for pkg in self._get_metadata('namespace_packages.txt'):
  2213. if pkg in sys.modules:
  2214. declare_namespace(pkg)
  2215. def egg_name(self):
  2216. """Return what this distribution's standard .egg filename should be"""
  2217. filename = "%s-%s-py%s" % (
  2218. to_filename(self.project_name), to_filename(self.version),
  2219. self.py_version or PY_MAJOR
  2220. )
  2221. if self.platform:
  2222. filename += '-' + self.platform
  2223. return filename
  2224. def __repr__(self):
  2225. if self.location:
  2226. return "%s (%s)" % (self, self.location)
  2227. else:
  2228. return str(self)
  2229. def __str__(self):
  2230. try:
  2231. version = getattr(self, 'version', None)
  2232. except ValueError:
  2233. version = None
  2234. version = version or "[unknown version]"
  2235. return "%s %s" % (self.project_name, version)
  2236. def __getattr__(self, attr):
  2237. """Delegate all unrecognized public attributes to .metadata provider"""
  2238. if attr.startswith('_'):
  2239. raise AttributeError(attr)
  2240. return getattr(self._provider, attr)
  2241. def __dir__(self):
  2242. return list(
  2243. set(super(Distribution, self).__dir__())
  2244. | set(
  2245. attr for attr in self._provider.__dir__()
  2246. if not attr.startswith('_')
  2247. )
  2248. )
  2249. @classmethod
  2250. def from_filename(cls, filename, metadata=None, **kw):
  2251. return cls.from_location(
  2252. _normalize_cached(filename), os.path.basename(filename), metadata,
  2253. **kw
  2254. )
  2255. def as_requirement(self):
  2256. """Return a ``Requirement`` that matches this distribution exactly"""
  2257. if isinstance(self.parsed_version, packaging.version.Version):
  2258. spec = "%s==%s" % (self.project_name, self.parsed_version)
  2259. else:
  2260. spec = "%s===%s" % (self.project_name, self.parsed_version)
  2261. return Requirement.parse(spec)
  2262. def load_entry_point(self, group, name):
  2263. """Return the `name` entry point of `group` or raise ImportError"""
  2264. ep = self.get_entry_info(group, name)
  2265. if ep is None:
  2266. raise ImportError("Entry point %r not found" % ((group, name),))
  2267. return ep.load()
  2268. def get_entry_map(self, group=None):
  2269. """Return the entry point map for `group`, or the full entry map"""
  2270. try:
  2271. ep_map = self._ep_map
  2272. except AttributeError:
  2273. ep_map = self._ep_map = EntryPoint.parse_map(
  2274. self._get_metadata('entry_points.txt'), self
  2275. )
  2276. if group is not None:
  2277. return ep_map.get(group, {})
  2278. return ep_map
  2279. def get_entry_info(self, group, name):
  2280. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  2281. return self.get_entry_map(group).get(name)
  2282. # FIXME: 'Distribution.insert_on' is too complex (13)
  2283. def insert_on(self, path, loc=None, replace=False): # noqa: C901
  2284. """Ensure self.location is on path
  2285. If replace=False (default):
  2286. - If location is already in path anywhere, do nothing.
  2287. - Else:
  2288. - If it's an egg and its parent directory is on path,
  2289. insert just ahead of the parent.
  2290. - Else: add to the end of path.
  2291. If replace=True:
  2292. - If location is already on path anywhere (not eggs)
  2293. or higher priority than its parent (eggs)
  2294. do nothing.
  2295. - Else:
  2296. - If it's an egg and its parent directory is on path,
  2297. insert just ahead of the parent,
  2298. removing any lower-priority entries.
  2299. - Else: add it to the front of path.
  2300. """
  2301. loc = loc or self.location
  2302. if not loc:
  2303. return
  2304. nloc = _normalize_cached(loc)
  2305. bdir = os.path.dirname(nloc)
  2306. npath = [(p and _normalize_cached(p) or p) for p in path]
  2307. for p, item in enumerate(npath):
  2308. if item == nloc:
  2309. if replace:
  2310. break
  2311. else:
  2312. # don't modify path (even removing duplicates) if
  2313. # found and not replace
  2314. return
  2315. elif item == bdir and self.precedence == EGG_DIST:
  2316. # if it's an .egg, give it precedence over its directory
  2317. # UNLESS it's already been added to sys.path and replace=False
  2318. if (not replace) and nloc in npath[p:]:
  2319. return
  2320. if path is sys.path:
  2321. self.check_version_conflict()
  2322. path.insert(p, loc)
  2323. npath.insert(p, nloc)
  2324. break
  2325. else:
  2326. if path is sys.path:
  2327. self.check_version_conflict()
  2328. if replace:
  2329. path.insert(0, loc)
  2330. else:
  2331. path.append(loc)
  2332. return
  2333. # p is the spot where we found or inserted loc; now remove duplicates
  2334. while True:
  2335. try:
  2336. np = npath.index(nloc, p + 1)
  2337. except ValueError:
  2338. break
  2339. else:
  2340. del npath[np], path[np]
  2341. # ha!
  2342. p = np
  2343. return
  2344. def check_version_conflict(self):
  2345. if self.key == 'setuptools':
  2346. # ignore the inevitable setuptools self-conflicts :(
  2347. return
  2348. nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
  2349. loc = normalize_path(self.location)
  2350. for modname in self._get_metadata('top_level.txt'):
  2351. if (modname not in sys.modules or modname in nsp
  2352. or modname in _namespace_packages):
  2353. continue
  2354. if modname in ('pkg_resources', 'setuptools', 'site'):
  2355. continue
  2356. fn = getattr(sys.modules[modname], '__file__', None)
  2357. if fn and (normalize_path(fn).startswith(loc) or
  2358. fn.startswith(self.location)):
  2359. continue
  2360. issue_warning(
  2361. "Module %s was already imported from %s, but %s is being added"
  2362. " to sys.path" % (modname, fn, self.location),
  2363. )
  2364. def has_version(self):
  2365. try:
  2366. self.version
  2367. except ValueError:
  2368. issue_warning("Unbuilt egg for " + repr(self))
  2369. return False
  2370. return True
  2371. def clone(self, **kw):
  2372. """Copy this distribution, substituting in any changed keyword args"""
  2373. names = 'project_name version py_version platform location precedence'
  2374. for attr in names.split():
  2375. kw.setdefault(attr, getattr(self, attr, None))
  2376. kw.setdefault('metadata', self._provider)
  2377. return self.__class__(**kw)
  2378. @property
  2379. def extras(self):
  2380. return [dep for dep in self._dep_map if dep]
  2381. class EggInfoDistribution(Distribution):
  2382. def _reload_version(self):
  2383. """
  2384. Packages installed by distutils (e.g. numpy or scipy),
  2385. which uses an old safe_version, and so
  2386. their version numbers can get mangled when
  2387. converted to filenames (e.g., 1.11.0.dev0+2329eae to
  2388. 1.11.0.dev0_2329eae). These distributions will not be
  2389. parsed properly
  2390. downstream by Distribution and safe_version, so
  2391. take an extra step and try to get the version number from
  2392. the metadata file itself instead of the filename.
  2393. """
  2394. md_version = self._get_version()
  2395. if md_version:
  2396. self._version = md_version
  2397. return self
  2398. class DistInfoDistribution(Distribution):
  2399. """
  2400. Wrap an actual or potential sys.path entry
  2401. w/metadata, .dist-info style.
  2402. """
  2403. PKG_INFO = 'METADATA'
  2404. EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
  2405. @property
  2406. def _parsed_pkg_info(self):
  2407. """Parse and cache metadata"""
  2408. try:
  2409. return self._pkg_info
  2410. except AttributeError:
  2411. metadata = self.get_metadata(self.PKG_INFO)
  2412. self._pkg_info = email.parser.Parser().parsestr(metadata)
  2413. return self._pkg_info
  2414. @property
  2415. def _dep_map(self):
  2416. try:
  2417. return self.__dep_map
  2418. except AttributeError:
  2419. self.__dep_map = self._compute_dependencies()
  2420. return self.__dep_map
  2421. def _compute_dependencies(self):
  2422. """Recompute this distribution's dependencies."""
  2423. dm = self.__dep_map = {None: []}
  2424. reqs = []
  2425. # Including any condition expressions
  2426. for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
  2427. reqs.extend(parse_requirements(req))
  2428. def reqs_for_extra(extra):
  2429. for req in reqs:
  2430. if not req.marker or req.marker.evaluate({'extra': extra}):
  2431. yield req
  2432. common = frozenset(reqs_for_extra(None))
  2433. dm[None].extend(common)
  2434. for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
  2435. s_extra = safe_extra(extra.strip())
  2436. dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
  2437. return dm
  2438. _distributionImpl = {
  2439. '.egg': Distribution,
  2440. '.egg-info': EggInfoDistribution,
  2441. '.dist-info': DistInfoDistribution,
  2442. }
  2443. def issue_warning(*args, **kw):
  2444. level = 1
  2445. g = globals()
  2446. try:
  2447. # find the first stack frame that is *not* code in
  2448. # the pkg_resources module, to use for the warning
  2449. while sys._getframe(level).f_globals is g:
  2450. level += 1
  2451. except ValueError:
  2452. pass
  2453. warnings.warn(stacklevel=level + 1, *args, **kw)
  2454. def parse_requirements(strs):
  2455. """Yield ``Requirement`` objects for each specification in `strs`
  2456. `strs` must be a string, or a (possibly-nested) iterable thereof.
  2457. """
  2458. # create a steppable iterator, so we can handle \-continuations
  2459. lines = iter(yield_lines(strs))
  2460. for line in lines:
  2461. # Drop comments -- a hash without a space may be in a URL.
  2462. if ' #' in line:
  2463. line = line[:line.find(' #')]
  2464. # If there is a line continuation, drop it, and append the next line.
  2465. if line.endswith('\\'):
  2466. line = line[:-2].strip()
  2467. try:
  2468. line += next(lines)
  2469. except StopIteration:
  2470. return
  2471. yield Requirement(line)
  2472. class RequirementParseError(packaging.requirements.InvalidRequirement):
  2473. "Compatibility wrapper for InvalidRequirement"
  2474. class Requirement(packaging.requirements.Requirement):
  2475. def __init__(self, requirement_string):
  2476. """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
  2477. super(Requirement, self).__init__(requirement_string)
  2478. self.unsafe_name = self.name
  2479. project_name = safe_name(self.name)
  2480. self.project_name, self.key = project_name, project_name.lower()
  2481. self.specs = [
  2482. (spec.operator, spec.version) for spec in self.specifier]
  2483. self.extras = tuple(map(safe_extra, self.extras))
  2484. self.hashCmp = (
  2485. self.key,
  2486. self.url,
  2487. self.specifier,
  2488. frozenset(self.extras),
  2489. str(self.marker) if self.marker else None,
  2490. )
  2491. self.__hash = hash(self.hashCmp)
  2492. def __eq__(self, other):
  2493. return (
  2494. isinstance(other, Requirement) and
  2495. self.hashCmp == other.hashCmp
  2496. )
  2497. def __ne__(self, other):
  2498. return not self == other
  2499. def __contains__(self, item):
  2500. if isinstance(item, Distribution):
  2501. if item.key != self.key:
  2502. return False
  2503. item = item.version
  2504. # Allow prereleases always in order to match the previous behavior of
  2505. # this method. In the future this should be smarter and follow PEP 440
  2506. # more accurately.
  2507. return self.specifier.contains(item, prereleases=True)
  2508. def __hash__(self):
  2509. return self.__hash
  2510. def __repr__(self):
  2511. return "Requirement.parse(%r)" % str(self)
  2512. @staticmethod
  2513. def parse(s):
  2514. req, = parse_requirements(s)
  2515. return req
  2516. def _always_object(classes):
  2517. """
  2518. Ensure object appears in the mro even
  2519. for old-style classes.
  2520. """
  2521. if object not in classes:
  2522. return classes + (object,)
  2523. return classes
  2524. def _find_adapter(registry, ob):
  2525. """Return an adapter factory for `ob` from `registry`"""
  2526. types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
  2527. for t in types:
  2528. if t in registry:
  2529. return registry[t]
  2530. def ensure_directory(path):
  2531. """Ensure that the parent directory of `path` exists"""
  2532. dirname = os.path.dirname(path)
  2533. os.makedirs(dirname, exist_ok=True)
  2534. def _bypass_ensure_directory(path):
  2535. """Sandbox-bypassing version of ensure_directory()"""
  2536. if not WRITE_SUPPORT:
  2537. raise IOError('"os.mkdir" not supported on this platform.')
  2538. dirname, filename = split(path)
  2539. if dirname and filename and not isdir(dirname):
  2540. _bypass_ensure_directory(dirname)
  2541. try:
  2542. mkdir(dirname, 0o755)
  2543. except FileExistsError:
  2544. pass
  2545. def split_sections(s):
  2546. """Split a string or iterable thereof into (section, content) pairs
  2547. Each ``section`` is a stripped version of the section header ("[section]")
  2548. and each ``content`` is a list of stripped lines excluding blank lines and
  2549. comment-only lines. If there are any such lines before the first section
  2550. header, they're returned in a first ``section`` of ``None``.
  2551. """
  2552. section = None
  2553. content = []
  2554. for line in yield_lines(s):
  2555. if line.startswith("["):
  2556. if line.endswith("]"):
  2557. if section or content:
  2558. yield section, content
  2559. section = line[1:-1].strip()
  2560. content = []
  2561. else:
  2562. raise ValueError("Invalid section heading", line)
  2563. else:
  2564. content.append(line)
  2565. # wrap up last segment
  2566. yield section, content
  2567. def _mkstemp(*args, **kw):
  2568. old_open = os.open
  2569. try:
  2570. # temporarily bypass sandboxing
  2571. os.open = os_open
  2572. return tempfile.mkstemp(*args, **kw)
  2573. finally:
  2574. # and then put it back
  2575. os.open = old_open
  2576. # Silence the PEP440Warning by default, so that end users don't get hit by it
  2577. # randomly just because they use pkg_resources. We want to append the rule
  2578. # because we want earlier uses of filterwarnings to take precedence over this
  2579. # one.
  2580. warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
  2581. # from jaraco.functools 1.3
  2582. def _call_aside(f, *args, **kwargs):
  2583. f(*args, **kwargs)
  2584. return f
  2585. @_call_aside
  2586. def _initialize(g=globals()):
  2587. "Set up global resource manager (deliberately not state-saved)"
  2588. manager = ResourceManager()
  2589. g['_manager'] = manager
  2590. g.update(
  2591. (name, getattr(manager, name))
  2592. for name in dir(manager)
  2593. if not name.startswith('_')
  2594. )
  2595. @_call_aside
  2596. def _initialize_master_working_set():
  2597. """
  2598. Prepare the master working set and make the ``require()``
  2599. API available.
  2600. This function has explicit effects on the global state
  2601. of pkg_resources. It is intended to be invoked once at
  2602. the initialization of this module.
  2603. Invocation by other packages is unsupported and done
  2604. at their own risk.
  2605. """
  2606. working_set = WorkingSet._build_master()
  2607. _declare_state('object', working_set=working_set)
  2608. require = working_set.require
  2609. iter_entry_points = working_set.iter_entry_points
  2610. add_activation_listener = working_set.subscribe
  2611. run_script = working_set.run_script
  2612. # backward compatibility
  2613. run_main = run_script
  2614. # Activate all distributions already on sys.path with replace=False and
  2615. # ensure that all distributions added to the working set in the future
  2616. # (e.g. by calling ``require()``) will get activated as well,
  2617. # with higher priority (replace=True).
  2618. tuple(
  2619. dist.activate(replace=False)
  2620. for dist in working_set
  2621. )
  2622. add_activation_listener(
  2623. lambda dist: dist.activate(replace=True),
  2624. existing=False,
  2625. )
  2626. working_set.entries = []
  2627. # match order
  2628. list(map(working_set.add_entry, sys.path))
  2629. globals().update(locals())
  2630. class PkgResourcesDeprecationWarning(Warning):
  2631. """
  2632. Base class for warning about deprecations in ``pkg_resources``
  2633. This class is not derived from ``DeprecationWarning``, and as such is
  2634. visible by default.
  2635. """