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.

3171 lines
102 KiB

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