PageRenderTime 54ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/pymode/libs/pkg_resources/__init__.py

https://gitlab.com/vim-IDE/python-mode
Python | 1436 lines | 1333 code | 58 blank | 45 comment | 55 complexity | a5070aaf5416cf2f0c9bf27ddd60f0a9 MD5 | raw file
  1. """
  2. Package resource API
  3. --------------------
  4. A resource is a logical file contained within a package, or a logical
  5. subdirectory thereof. The package resource API expects resource names
  6. to have their path parts separated with ``/``, *not* whatever the local
  7. path separator is. Do not use os.path operations to manipulate resource
  8. names being passed into the API.
  9. The package resource API is designed to work with normal filesystem packages,
  10. .egg files, and unpacked .egg files. It can also work in a limited way with
  11. .zip files and with custom PEP 302 loaders that support the ``get_data()``
  12. method.
  13. """
  14. from __future__ import absolute_import
  15. import sys
  16. import os
  17. import io
  18. import time
  19. import re
  20. import types
  21. import zipfile
  22. import zipimport
  23. import warnings
  24. import stat
  25. import functools
  26. import pkgutil
  27. import token
  28. import symbol
  29. import operator
  30. import platform
  31. import collections
  32. import plistlib
  33. import email.parser
  34. import tempfile
  35. import textwrap
  36. from pkgutil import get_importer
  37. try:
  38. import _imp
  39. except ImportError:
  40. # Python 3.2 compatibility
  41. import imp as _imp
  42. PY3 = sys.version_info > (3,)
  43. PY2 = not PY3
  44. if PY3:
  45. from urllib.parse import urlparse, urlunparse
  46. if PY2:
  47. from urlparse import urlparse, urlunparse
  48. if PY3:
  49. string_types = str,
  50. else:
  51. string_types = str, eval('unicode')
  52. iteritems = (lambda i: i.items()) if PY3 else lambda i: i.iteritems()
  53. # capture these to bypass sandboxing
  54. from os import utime
  55. try:
  56. from os import mkdir, rename, unlink
  57. WRITE_SUPPORT = True
  58. except ImportError:
  59. # no write support, probably under GAE
  60. WRITE_SUPPORT = False
  61. from os import open as os_open
  62. from os.path import isdir, split
  63. # Avoid try/except due to potential problems with delayed import mechanisms.
  64. if sys.version_info >= (3, 3) and sys.implementation.name == "cpython":
  65. import importlib.machinery as importlib_machinery
  66. else:
  67. importlib_machinery = None
  68. try:
  69. import parser
  70. except ImportError:
  71. pass
  72. try:
  73. import pkg_resources._vendor.packaging.version
  74. import pkg_resources._vendor.packaging.specifiers
  75. packaging = pkg_resources._vendor.packaging
  76. except ImportError:
  77. # fallback to naturally-installed version; allows system packagers to
  78. # omit vendored packages.
  79. import packaging.version
  80. import packaging.specifiers
  81. # declare some globals that will be defined later to
  82. # satisfy the linters.
  83. require = None
  84. working_set = None
  85. class PEP440Warning(RuntimeWarning):
  86. """
  87. Used when there is an issue with a version or specifier not complying with
  88. PEP 440.
  89. """
  90. class _SetuptoolsVersionMixin(object):
  91. def __hash__(self):
  92. return super(_SetuptoolsVersionMixin, self).__hash__()
  93. def __lt__(self, other):
  94. if isinstance(other, tuple):
  95. return tuple(self) < other
  96. else:
  97. return super(_SetuptoolsVersionMixin, self).__lt__(other)
  98. def __le__(self, other):
  99. if isinstance(other, tuple):
  100. return tuple(self) <= other
  101. else:
  102. return super(_SetuptoolsVersionMixin, self).__le__(other)
  103. def __eq__(self, other):
  104. if isinstance(other, tuple):
  105. return tuple(self) == other
  106. else:
  107. return super(_SetuptoolsVersionMixin, self).__eq__(other)
  108. def __ge__(self, other):
  109. if isinstance(other, tuple):
  110. return tuple(self) >= other
  111. else:
  112. return super(_SetuptoolsVersionMixin, self).__ge__(other)
  113. def __gt__(self, other):
  114. if isinstance(other, tuple):
  115. return tuple(self) > other
  116. else:
  117. return super(_SetuptoolsVersionMixin, self).__gt__(other)
  118. def __ne__(self, other):
  119. if isinstance(other, tuple):
  120. return tuple(self) != other
  121. else:
  122. return super(_SetuptoolsVersionMixin, self).__ne__(other)
  123. def __getitem__(self, key):
  124. return tuple(self)[key]
  125. def __iter__(self):
  126. component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
  127. replace = {
  128. 'pre': 'c',
  129. 'preview': 'c',
  130. '-': 'final-',
  131. 'rc': 'c',
  132. 'dev': '@',
  133. }.get
  134. def _parse_version_parts(s):
  135. for part in component_re.split(s):
  136. part = replace(part, part)
  137. if not part or part == '.':
  138. continue
  139. if part[:1] in '0123456789':
  140. # pad for numeric comparison
  141. yield part.zfill(8)
  142. else:
  143. yield '*'+part
  144. # ensure that alpha/beta/candidate are before final
  145. yield '*final'
  146. def old_parse_version(s):
  147. parts = []
  148. for part in _parse_version_parts(s.lower()):
  149. if part.startswith('*'):
  150. # remove '-' before a prerelease tag
  151. if part < '*final':
  152. while parts and parts[-1] == '*final-':
  153. parts.pop()
  154. # remove trailing zeros from each series of numeric parts
  155. while parts and parts[-1] == '00000000':
  156. parts.pop()
  157. parts.append(part)
  158. return tuple(parts)
  159. # Warn for use of this function
  160. warnings.warn(
  161. "You have iterated over the result of "
  162. "pkg_resources.parse_version. This is a legacy behavior which is "
  163. "inconsistent with the new version class introduced in setuptools "
  164. "8.0. In most cases, conversion to a tuple is unnecessary. For "
  165. "comparison of versions, sort the Version instances directly. If "
  166. "you have another use case requiring the tuple, please file a "
  167. "bug with the setuptools project describing that need.",
  168. RuntimeWarning,
  169. stacklevel=1,
  170. )
  171. for part in old_parse_version(str(self)):
  172. yield part
  173. class SetuptoolsVersion(_SetuptoolsVersionMixin, packaging.version.Version):
  174. pass
  175. class SetuptoolsLegacyVersion(_SetuptoolsVersionMixin,
  176. packaging.version.LegacyVersion):
  177. pass
  178. def parse_version(v):
  179. try:
  180. return SetuptoolsVersion(v)
  181. except packaging.version.InvalidVersion:
  182. return SetuptoolsLegacyVersion(v)
  183. _state_vars = {}
  184. def _declare_state(vartype, **kw):
  185. globals().update(kw)
  186. _state_vars.update(dict.fromkeys(kw, vartype))
  187. def __getstate__():
  188. state = {}
  189. g = globals()
  190. for k, v in _state_vars.items():
  191. state[k] = g['_sget_'+v](g[k])
  192. return state
  193. def __setstate__(state):
  194. g = globals()
  195. for k, v in state.items():
  196. g['_sset_'+_state_vars[k]](k, g[k], v)
  197. return state
  198. def _sget_dict(val):
  199. return val.copy()
  200. def _sset_dict(key, ob, state):
  201. ob.clear()
  202. ob.update(state)
  203. def _sget_object(val):
  204. return val.__getstate__()
  205. def _sset_object(key, ob, state):
  206. ob.__setstate__(state)
  207. _sget_none = _sset_none = lambda *args: None
  208. def get_supported_platform():
  209. """Return this platform's maximum compatible version.
  210. distutils.util.get_platform() normally reports the minimum version
  211. of Mac OS X that would be required to *use* extensions produced by
  212. distutils. But what we want when checking compatibility is to know the
  213. version of Mac OS X that we are *running*. To allow usage of packages that
  214. explicitly require a newer version of Mac OS X, we must also know the
  215. current version of the OS.
  216. If this condition occurs for any other platform with a version in its
  217. platform strings, this function should be extended accordingly.
  218. """
  219. plat = get_build_platform()
  220. m = macosVersionString.match(plat)
  221. if m is not None and sys.platform == "darwin":
  222. try:
  223. plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
  224. except ValueError:
  225. # not Mac OS X
  226. pass
  227. return plat
  228. __all__ = [
  229. # Basic resource access and distribution/entry point discovery
  230. 'require', 'run_script', 'get_provider', 'get_distribution',
  231. 'load_entry_point', 'get_entry_map', 'get_entry_info',
  232. 'iter_entry_points',
  233. 'resource_string', 'resource_stream', 'resource_filename',
  234. 'resource_listdir', 'resource_exists', 'resource_isdir',
  235. # Environmental control
  236. 'declare_namespace', 'working_set', 'add_activation_listener',
  237. 'find_distributions', 'set_extraction_path', 'cleanup_resources',
  238. 'get_default_cache',
  239. # Primary implementation classes
  240. 'Environment', 'WorkingSet', 'ResourceManager',
  241. 'Distribution', 'Requirement', 'EntryPoint',
  242. # Exceptions
  243. 'ResolutionError', 'VersionConflict', 'DistributionNotFound',
  244. 'UnknownExtra', 'ExtractionError',
  245. # Warnings
  246. 'PEP440Warning',
  247. # Parsing functions and string utilities
  248. 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
  249. 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
  250. 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
  251. # filesystem utilities
  252. 'ensure_directory', 'normalize_path',
  253. # Distribution "precedence" constants
  254. 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
  255. # "Provider" interfaces, implementations, and registration/lookup APIs
  256. 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
  257. 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
  258. 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
  259. 'register_finder', 'register_namespace_handler', 'register_loader_type',
  260. 'fixup_namespace_packages', 'get_importer',
  261. # Deprecated/backward compatibility only
  262. 'run_main', 'AvailableDistributions',
  263. ]
  264. class ResolutionError(Exception):
  265. """Abstract base for dependency resolution errors"""
  266. def __repr__(self):
  267. return self.__class__.__name__+repr(self.args)
  268. class VersionConflict(ResolutionError):
  269. """
  270. An already-installed version conflicts with the requested version.
  271. Should be initialized with the installed Distribution and the requested
  272. Requirement.
  273. """
  274. _template = "{self.dist} is installed but {self.req} is required"
  275. @property
  276. def dist(self):
  277. return self.args[0]
  278. @property
  279. def req(self):
  280. return self.args[1]
  281. def report(self):
  282. return self._template.format(**locals())
  283. def with_context(self, required_by):
  284. """
  285. If required_by is non-empty, return a version of self that is a
  286. ContextualVersionConflict.
  287. """
  288. if not required_by:
  289. return self
  290. args = self.args + (required_by,)
  291. return ContextualVersionConflict(*args)
  292. class ContextualVersionConflict(VersionConflict):
  293. """
  294. A VersionConflict that accepts a third parameter, the set of the
  295. requirements that required the installed Distribution.
  296. """
  297. _template = VersionConflict._template + ' by {self.required_by}'
  298. @property
  299. def required_by(self):
  300. return self.args[2]
  301. class DistributionNotFound(ResolutionError):
  302. """A requested distribution was not found"""
  303. _template = ("The '{self.req}' distribution was not found "
  304. "and is required by {self.requirers_str}")
  305. @property
  306. def req(self):
  307. return self.args[0]
  308. @property
  309. def requirers(self):
  310. return self.args[1]
  311. @property
  312. def requirers_str(self):
  313. if not self.requirers:
  314. return 'the application'
  315. return ', '.join(self.requirers)
  316. def report(self):
  317. return self._template.format(**locals())
  318. def __str__(self):
  319. return self.report()
  320. class UnknownExtra(ResolutionError):
  321. """Distribution doesn't have an "extra feature" of the given name"""
  322. _provider_factories = {}
  323. PY_MAJOR = sys.version[:3]
  324. EGG_DIST = 3
  325. BINARY_DIST = 2
  326. SOURCE_DIST = 1
  327. CHECKOUT_DIST = 0
  328. DEVELOP_DIST = -1
  329. def register_loader_type(loader_type, provider_factory):
  330. """Register `provider_factory` to make providers for `loader_type`
  331. `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
  332. and `provider_factory` is a function that, passed a *module* object,
  333. returns an ``IResourceProvider`` for that module.
  334. """
  335. _provider_factories[loader_type] = provider_factory
  336. def get_provider(moduleOrReq):
  337. """Return an IResourceProvider for the named module or requirement"""
  338. if isinstance(moduleOrReq, Requirement):
  339. return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  340. try:
  341. module = sys.modules[moduleOrReq]
  342. except KeyError:
  343. __import__(moduleOrReq)
  344. module = sys.modules[moduleOrReq]
  345. loader = getattr(module, '__loader__', None)
  346. return _find_adapter(_provider_factories, loader)(module)
  347. def _macosx_vers(_cache=[]):
  348. if not _cache:
  349. version = platform.mac_ver()[0]
  350. # fallback for MacPorts
  351. if version == '':
  352. plist = '/System/Library/CoreServices/SystemVersion.plist'
  353. if os.path.exists(plist):
  354. if hasattr(plistlib, 'readPlist'):
  355. plist_content = plistlib.readPlist(plist)
  356. if 'ProductVersion' in plist_content:
  357. version = plist_content['ProductVersion']
  358. _cache.append(version.split('.'))
  359. return _cache[0]
  360. def _macosx_arch(machine):
  361. return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
  362. def get_build_platform():
  363. """Return this platform's string for platform-specific distributions
  364. XXX Currently this is the same as ``distutils.util.get_platform()``, but it
  365. needs some hacks for Linux and Mac OS X.
  366. """
  367. try:
  368. # Python 2.7 or >=3.2
  369. from sysconfig import get_platform
  370. except ImportError:
  371. from distutils.util import get_platform
  372. plat = get_platform()
  373. if sys.platform == "darwin" and not plat.startswith('macosx-'):
  374. try:
  375. version = _macosx_vers()
  376. machine = os.uname()[4].replace(" ", "_")
  377. return "macosx-%d.%d-%s" % (int(version[0]), int(version[1]),
  378. _macosx_arch(machine))
  379. except ValueError:
  380. # if someone is running a non-Mac darwin system, this will fall
  381. # through to the default implementation
  382. pass
  383. return plat
  384. macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
  385. darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
  386. # XXX backward compat
  387. get_platform = get_build_platform
  388. def compatible_platforms(provided, required):
  389. """Can code for the `provided` platform run on the `required` platform?
  390. Returns true if either platform is ``None``, or the platforms are equal.
  391. XXX Needs compatibility checks for Linux and other unixy OSes.
  392. """
  393. if provided is None or required is None or provided==required:
  394. # easy case
  395. return True
  396. # Mac OS X special cases
  397. reqMac = macosVersionString.match(required)
  398. if reqMac:
  399. provMac = macosVersionString.match(provided)
  400. # is this a Mac package?
  401. if not provMac:
  402. # this is backwards compatibility for packages built before
  403. # setuptools 0.6. All packages built after this point will
  404. # use the new macosx designation.
  405. provDarwin = darwinVersionString.match(provided)
  406. if provDarwin:
  407. dversion = int(provDarwin.group(1))
  408. macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
  409. if dversion == 7 and macosversion >= "10.3" or \
  410. dversion == 8 and macosversion >= "10.4":
  411. return True
  412. # egg isn't macosx or legacy darwin
  413. return False
  414. # are they the same major version and machine type?
  415. if provMac.group(1) != reqMac.group(1) or \
  416. provMac.group(3) != reqMac.group(3):
  417. return False
  418. # is the required OS major update >= the provided one?
  419. if int(provMac.group(2)) > int(reqMac.group(2)):
  420. return False
  421. return True
  422. # XXX Linux and other platforms' special cases should go here
  423. return False
  424. def run_script(dist_spec, script_name):
  425. """Locate distribution `dist_spec` and run its `script_name` script"""
  426. ns = sys._getframe(1).f_globals
  427. name = ns['__name__']
  428. ns.clear()
  429. ns['__name__'] = name
  430. require(dist_spec)[0].run_script(script_name, ns)
  431. # backward compatibility
  432. run_main = run_script
  433. def get_distribution(dist):
  434. """Return a current distribution object for a Requirement or string"""
  435. if isinstance(dist, string_types):
  436. dist = Requirement.parse(dist)
  437. if isinstance(dist, Requirement):
  438. dist = get_provider(dist)
  439. if not isinstance(dist, Distribution):
  440. raise TypeError("Expected string, Requirement, or Distribution", dist)
  441. return dist
  442. def load_entry_point(dist, group, name):
  443. """Return `name` entry point of `group` for `dist` or raise ImportError"""
  444. return get_distribution(dist).load_entry_point(group, name)
  445. def get_entry_map(dist, group=None):
  446. """Return the entry point map for `group`, or the full entry map"""
  447. return get_distribution(dist).get_entry_map(group)
  448. def get_entry_info(dist, group, name):
  449. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  450. return get_distribution(dist).get_entry_info(group, name)
  451. class IMetadataProvider:
  452. def has_metadata(name):
  453. """Does the package's distribution contain the named metadata?"""
  454. def get_metadata(name):
  455. """The named metadata resource as a string"""
  456. def get_metadata_lines(name):
  457. """Yield named metadata resource as list of non-blank non-comment lines
  458. Leading and trailing whitespace is stripped from each line, and lines
  459. with ``#`` as the first non-blank character are omitted."""
  460. def metadata_isdir(name):
  461. """Is the named metadata a directory? (like ``os.path.isdir()``)"""
  462. def metadata_listdir(name):
  463. """List of metadata names in the directory (like ``os.listdir()``)"""
  464. def run_script(script_name, namespace):
  465. """Execute the named script in the supplied namespace dictionary"""
  466. class IResourceProvider(IMetadataProvider):
  467. """An object that provides access to package resources"""
  468. def get_resource_filename(manager, resource_name):
  469. """Return a true filesystem path for `resource_name`
  470. `manager` must be an ``IResourceManager``"""
  471. def get_resource_stream(manager, resource_name):
  472. """Return a readable file-like object for `resource_name`
  473. `manager` must be an ``IResourceManager``"""
  474. def get_resource_string(manager, resource_name):
  475. """Return a string containing the contents of `resource_name`
  476. `manager` must be an ``IResourceManager``"""
  477. def has_resource(resource_name):
  478. """Does the package contain the named resource?"""
  479. def resource_isdir(resource_name):
  480. """Is the named resource a directory? (like ``os.path.isdir()``)"""
  481. def resource_listdir(resource_name):
  482. """List of resource names in the directory (like ``os.listdir()``)"""
  483. class WorkingSet(object):
  484. """A collection of active distributions on sys.path (or a similar list)"""
  485. def __init__(self, entries=None):
  486. """Create working set from list of path entries (default=sys.path)"""
  487. self.entries = []
  488. self.entry_keys = {}
  489. self.by_key = {}
  490. self.callbacks = []
  491. if entries is None:
  492. entries = sys.path
  493. for entry in entries:
  494. self.add_entry(entry)
  495. @classmethod
  496. def _build_master(cls):
  497. """
  498. Prepare the master working set.
  499. """
  500. ws = cls()
  501. try:
  502. from __main__ import __requires__
  503. except ImportError:
  504. # The main program does not list any requirements
  505. return ws
  506. # ensure the requirements are met
  507. try:
  508. ws.require(__requires__)
  509. except VersionConflict:
  510. return cls._build_from_requirements(__requires__)
  511. return ws
  512. @classmethod
  513. def _build_from_requirements(cls, req_spec):
  514. """
  515. Build a working set from a requirement spec. Rewrites sys.path.
  516. """
  517. # try it without defaults already on sys.path
  518. # by starting with an empty path
  519. ws = cls([])
  520. reqs = parse_requirements(req_spec)
  521. dists = ws.resolve(reqs, Environment())
  522. for dist in dists:
  523. ws.add(dist)
  524. # add any missing entries from sys.path
  525. for entry in sys.path:
  526. if entry not in ws.entries:
  527. ws.add_entry(entry)
  528. # then copy back to sys.path
  529. sys.path[:] = ws.entries
  530. return ws
  531. def add_entry(self, entry):
  532. """Add a path item to ``.entries``, finding any distributions on it
  533. ``find_distributions(entry, True)`` is used to find distributions
  534. corresponding to the path entry, and they are added. `entry` is
  535. always appended to ``.entries``, even if it is already present.
  536. (This is because ``sys.path`` can contain the same value more than
  537. once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
  538. equal ``sys.path``.)
  539. """
  540. self.entry_keys.setdefault(entry, [])
  541. self.entries.append(entry)
  542. for dist in find_distributions(entry, True):
  543. self.add(dist, entry, False)
  544. def __contains__(self, dist):
  545. """True if `dist` is the active distribution for its project"""
  546. return self.by_key.get(dist.key) == dist
  547. def find(self, req):
  548. """Find a distribution matching requirement `req`
  549. If there is an active distribution for the requested project, this
  550. returns it as long as it meets the version requirement specified by
  551. `req`. But, if there is an active distribution for the project and it
  552. does *not* meet the `req` requirement, ``VersionConflict`` is raised.
  553. If there is no active distribution for the requested project, ``None``
  554. is returned.
  555. """
  556. dist = self.by_key.get(req.key)
  557. if dist is not None and dist not in req:
  558. # XXX add more info
  559. raise VersionConflict(dist, req)
  560. return dist
  561. def iter_entry_points(self, group, name=None):
  562. """Yield entry point objects from `group` matching `name`
  563. If `name` is None, yields all entry points in `group` from all
  564. distributions in the working set, otherwise only ones matching
  565. both `group` and `name` are yielded (in distribution order).
  566. """
  567. for dist in self:
  568. entries = dist.get_entry_map(group)
  569. if name is None:
  570. for ep in entries.values():
  571. yield ep
  572. elif name in entries:
  573. yield entries[name]
  574. def run_script(self, requires, script_name):
  575. """Locate distribution for `requires` and run `script_name` script"""
  576. ns = sys._getframe(1).f_globals
  577. name = ns['__name__']
  578. ns.clear()
  579. ns['__name__'] = name
  580. self.require(requires)[0].run_script(script_name, ns)
  581. def __iter__(self):
  582. """Yield distributions for non-duplicate projects in the working set
  583. The yield order is the order in which the items' path entries were
  584. added to the working set.
  585. """
  586. seen = {}
  587. for item in self.entries:
  588. if item not in self.entry_keys:
  589. # workaround a cache issue
  590. continue
  591. for key in self.entry_keys[item]:
  592. if key not in seen:
  593. seen[key]=1
  594. yield self.by_key[key]
  595. def add(self, dist, entry=None, insert=True, replace=False):
  596. """Add `dist` to working set, associated with `entry`
  597. If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
  598. On exit from this routine, `entry` is added to the end of the working
  599. set's ``.entries`` (if it wasn't already present).
  600. `dist` is only added to the working set if it's for a project that
  601. doesn't already have a distribution in the set, unless `replace=True`.
  602. If it's added, any callbacks registered with the ``subscribe()`` method
  603. will be called.
  604. """
  605. if insert:
  606. dist.insert_on(self.entries, entry)
  607. if entry is None:
  608. entry = dist.location
  609. keys = self.entry_keys.setdefault(entry,[])
  610. keys2 = self.entry_keys.setdefault(dist.location,[])
  611. if not replace and dist.key in self.by_key:
  612. # ignore hidden distros
  613. return
  614. self.by_key[dist.key] = dist
  615. if dist.key not in keys:
  616. keys.append(dist.key)
  617. if dist.key not in keys2:
  618. keys2.append(dist.key)
  619. self._added_new(dist)
  620. def resolve(self, requirements, env=None, installer=None,
  621. replace_conflicting=False):
  622. """List all distributions needed to (recursively) meet `requirements`
  623. `requirements` must be a sequence of ``Requirement`` objects. `env`,
  624. if supplied, should be an ``Environment`` instance. If
  625. not supplied, it defaults to all distributions available within any
  626. entry or distribution in the working set. `installer`, if supplied,
  627. will be invoked with each requirement that cannot be met by an
  628. already-installed distribution; it should return a ``Distribution`` or
  629. ``None``.
  630. Unless `replace_conflicting=True`, raises a VersionConflict exception if
  631. any requirements are found on the path that have the correct name but
  632. the wrong version. Otherwise, if an `installer` is supplied it will be
  633. invoked to obtain the correct version of the requirement and activate
  634. it.
  635. """
  636. # set up the stack
  637. requirements = list(requirements)[::-1]
  638. # set of processed requirements
  639. processed = {}
  640. # key -> dist
  641. best = {}
  642. to_activate = []
  643. # Mapping of requirement to set of distributions that required it;
  644. # useful for reporting info about conflicts.
  645. required_by = collections.defaultdict(set)
  646. while requirements:
  647. # process dependencies breadth-first
  648. req = requirements.pop(0)
  649. if req in processed:
  650. # Ignore cyclic or redundant dependencies
  651. continue
  652. dist = best.get(req.key)
  653. if dist is None:
  654. # Find the best distribution and add it to the map
  655. dist = self.by_key.get(req.key)
  656. if dist is None or (dist not in req and replace_conflicting):
  657. ws = self
  658. if env is None:
  659. if dist is None:
  660. env = Environment(self.entries)
  661. else:
  662. # Use an empty environment and workingset to avoid
  663. # any further conflicts with the conflicting
  664. # distribution
  665. env = Environment([])
  666. ws = WorkingSet([])
  667. dist = best[req.key] = env.best_match(req, ws, installer)
  668. if dist is None:
  669. requirers = required_by.get(req, None)
  670. raise DistributionNotFound(req, requirers)
  671. to_activate.append(dist)
  672. if dist not in req:
  673. # Oops, the "best" so far conflicts with a dependency
  674. dependent_req = required_by[req]
  675. raise VersionConflict(dist, req).with_context(dependent_req)
  676. # push the new requirements onto the stack
  677. new_requirements = dist.requires(req.extras)[::-1]
  678. requirements.extend(new_requirements)
  679. # Register the new requirements needed by req
  680. for new_requirement in new_requirements:
  681. required_by[new_requirement].add(req.project_name)
  682. processed[req] = True
  683. # return list of distros to activate
  684. return to_activate
  685. def find_plugins(self, plugin_env, full_env=None, installer=None,
  686. fallback=True):
  687. """Find all activatable distributions in `plugin_env`
  688. Example usage::
  689. distributions, errors = working_set.find_plugins(
  690. Environment(plugin_dirlist)
  691. )
  692. # add plugins+libs to sys.path
  693. map(working_set.add, distributions)
  694. # display errors
  695. print('Could not load', errors)
  696. The `plugin_env` should be an ``Environment`` instance that contains
  697. only distributions that are in the project's "plugin directory" or
  698. directories. The `full_env`, if supplied, should be an ``Environment``
  699. contains all currently-available distributions. If `full_env` is not
  700. supplied, one is created automatically from the ``WorkingSet`` this
  701. method is called on, which will typically mean that every directory on
  702. ``sys.path`` will be scanned for distributions.
  703. `installer` is a standard installer callback as used by the
  704. ``resolve()`` method. The `fallback` flag indicates whether we should
  705. attempt to resolve older versions of a plugin if the newest version
  706. cannot be resolved.
  707. This method returns a 2-tuple: (`distributions`, `error_info`), where
  708. `distributions` is a list of the distributions found in `plugin_env`
  709. that were loadable, along with any other distributions that are needed
  710. to resolve their dependencies. `error_info` is a dictionary mapping
  711. unloadable plugin distributions to an exception instance describing the
  712. error that occurred. Usually this will be a ``DistributionNotFound`` or
  713. ``VersionConflict`` instance.
  714. """
  715. plugin_projects = list(plugin_env)
  716. # scan project names in alphabetic order
  717. plugin_projects.sort()
  718. error_info = {}
  719. distributions = {}
  720. if full_env is None:
  721. env = Environment(self.entries)
  722. env += plugin_env
  723. else:
  724. env = full_env + plugin_env
  725. shadow_set = self.__class__([])
  726. # put all our entries in shadow_set
  727. list(map(shadow_set.add, self))
  728. for project_name in plugin_projects:
  729. for dist in plugin_env[project_name]:
  730. req = [dist.as_requirement()]
  731. try:
  732. resolvees = shadow_set.resolve(req, env, installer)
  733. except ResolutionError as v:
  734. # save error info
  735. error_info[dist] = v
  736. if fallback:
  737. # try the next older version of project
  738. continue
  739. else:
  740. # give up on this project, keep going
  741. break
  742. else:
  743. list(map(shadow_set.add, resolvees))
  744. distributions.update(dict.fromkeys(resolvees))
  745. # success, no need to try any more versions of this project
  746. break
  747. distributions = list(distributions)
  748. distributions.sort()
  749. return distributions, error_info
  750. def require(self, *requirements):
  751. """Ensure that distributions matching `requirements` are activated
  752. `requirements` must be a string or a (possibly-nested) sequence
  753. thereof, specifying the distributions and versions required. The
  754. return value is a sequence of the distributions that needed to be
  755. activated to fulfill the requirements; all relevant distributions are
  756. included, even if they were already activated in this working set.
  757. """
  758. needed = self.resolve(parse_requirements(requirements))
  759. for dist in needed:
  760. self.add(dist)
  761. return needed
  762. def subscribe(self, callback):
  763. """Invoke `callback` for all distributions (including existing ones)"""
  764. if callback in self.callbacks:
  765. return
  766. self.callbacks.append(callback)
  767. for dist in self:
  768. callback(dist)
  769. def _added_new(self, dist):
  770. for callback in self.callbacks:
  771. callback(dist)
  772. def __getstate__(self):
  773. return (
  774. self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
  775. self.callbacks[:]
  776. )
  777. def __setstate__(self, e_k_b_c):
  778. entries, keys, by_key, callbacks = e_k_b_c
  779. self.entries = entries[:]
  780. self.entry_keys = keys.copy()
  781. self.by_key = by_key.copy()
  782. self.callbacks = callbacks[:]
  783. class Environment(object):
  784. """Searchable snapshot of distributions on a search path"""
  785. def __init__(self, search_path=None, platform=get_supported_platform(),
  786. python=PY_MAJOR):
  787. """Snapshot distributions available on a search path
  788. Any distributions found on `search_path` are added to the environment.
  789. `search_path` should be a sequence of ``sys.path`` items. If not
  790. supplied, ``sys.path`` is used.
  791. `platform` is an optional string specifying the name of the platform
  792. that platform-specific distributions must be compatible with. If
  793. unspecified, it defaults to the current platform. `python` is an
  794. optional string naming the desired version of Python (e.g. ``'3.3'``);
  795. it defaults to the current version.
  796. You may explicitly set `platform` (and/or `python`) to ``None`` if you
  797. wish to map *all* distributions, not just those compatible with the
  798. running platform or Python version.
  799. """
  800. self._distmap = {}
  801. self.platform = platform
  802. self.python = python
  803. self.scan(search_path)
  804. def can_add(self, dist):
  805. """Is distribution `dist` acceptable for this environment?
  806. The distribution must match the platform and python version
  807. requirements specified when this environment was created, or False
  808. is returned.
  809. """
  810. return (self.python is None or dist.py_version is None
  811. or dist.py_version==self.python) \
  812. and compatible_platforms(dist.platform, self.platform)
  813. def remove(self, dist):
  814. """Remove `dist` from the environment"""
  815. self._distmap[dist.key].remove(dist)
  816. def scan(self, search_path=None):
  817. """Scan `search_path` for distributions usable in this environment
  818. Any distributions found are added to the environment.
  819. `search_path` should be a sequence of ``sys.path`` items. If not
  820. supplied, ``sys.path`` is used. Only distributions conforming to
  821. the platform/python version defined at initialization are added.
  822. """
  823. if search_path is None:
  824. search_path = sys.path
  825. for item in search_path:
  826. for dist in find_distributions(item):
  827. self.add(dist)
  828. def __getitem__(self, project_name):
  829. """Return a newest-to-oldest list of distributions for `project_name`
  830. Uses case-insensitive `project_name` comparison, assuming all the
  831. project's distributions use their project's name converted to all
  832. lowercase as their key.
  833. """
  834. distribution_key = project_name.lower()
  835. return self._distmap.get(distribution_key, [])
  836. def add(self, dist):
  837. """Add `dist` if we ``can_add()`` it and it has not already been added
  838. """
  839. if self.can_add(dist) and dist.has_version():
  840. dists = self._distmap.setdefault(dist.key, [])
  841. if dist not in dists:
  842. dists.append(dist)
  843. dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
  844. def best_match(self, req, working_set, installer=None):
  845. """Find distribution best matching `req` and usable on `working_set`
  846. This calls the ``find(req)`` method of the `working_set` to see if a
  847. suitable distribution is already active. (This may raise
  848. ``VersionConflict`` if an unsuitable version of the project is already
  849. active in the specified `working_set`.) If a suitable distribution
  850. isn't active, this method returns the newest distribution in the
  851. environment that meets the ``Requirement`` in `req`. If no suitable
  852. distribution is found, and `installer` is supplied, then the result of
  853. calling the environment's ``obtain(req, installer)`` method will be
  854. returned.
  855. """
  856. dist = working_set.find(req)
  857. if dist is not None:
  858. return dist
  859. for dist in self[req.key]:
  860. if dist in req:
  861. return dist
  862. # try to download/install
  863. return self.obtain(req, installer)
  864. def obtain(self, requirement, installer=None):
  865. """Obtain a distribution matching `requirement` (e.g. via download)
  866. Obtain a distro that matches requirement (e.g. via download). In the
  867. base ``Environment`` class, this routine just returns
  868. ``installer(requirement)``, unless `installer` is None, in which case
  869. None is returned instead. This method is a hook that allows subclasses
  870. to attempt other ways of obtaining a distribution before falling back
  871. to the `installer` argument."""
  872. if installer is not None:
  873. return installer(requirement)
  874. def __iter__(self):
  875. """Yield the unique project names of the available distributions"""
  876. for key in self._distmap.keys():
  877. if self[key]:
  878. yield key
  879. def __iadd__(self, other):
  880. """In-place addition of a distribution or environment"""
  881. if isinstance(other, Distribution):
  882. self.add(other)
  883. elif isinstance(other, Environment):
  884. for project in other:
  885. for dist in other[project]:
  886. self.add(dist)
  887. else:
  888. raise TypeError("Can't add %r to environment" % (other,))
  889. return self
  890. def __add__(self, other):
  891. """Add an environment or distribution to an environment"""
  892. new = self.__class__([], platform=None, python=None)
  893. for env in self, other:
  894. new += env
  895. return new
  896. # XXX backward compatibility
  897. AvailableDistributions = Environment
  898. class ExtractionError(RuntimeError):
  899. """An error occurred extracting a resource
  900. The following attributes are available from instances of this exception:
  901. manager
  902. The resource manager that raised this exception
  903. cache_path
  904. The base directory for resource extraction
  905. original_error
  906. The exception instance that caused extraction to fail
  907. """
  908. class ResourceManager:
  909. """Manage resource extraction and packages"""
  910. extraction_path = None
  911. def __init__(self):
  912. self.cached_files = {}
  913. def resource_exists(self, package_or_requirement, resource_name):
  914. """Does the named resource exist?"""
  915. return get_provider(package_or_requirement).has_resource(resource_name)
  916. def resource_isdir(self, package_or_requirement, resource_name):
  917. """Is the named resource an existing directory?"""
  918. return get_provider(package_or_requirement).resource_isdir(
  919. resource_name
  920. )
  921. def resource_filename(self, package_or_requirement, resource_name):
  922. """Return a true filesystem path for specified resource"""
  923. return get_provider(package_or_requirement).get_resource_filename(
  924. self, resource_name
  925. )
  926. def resource_stream(self, package_or_requirement, resource_name):
  927. """Return a readable file-like object for specified resource"""
  928. return get_provider(package_or_requirement).get_resource_stream(
  929. self, resource_name
  930. )
  931. def resource_string(self, package_or_requirement, resource_name):
  932. """Return specified resource as a string"""
  933. return get_provider(package_or_requirement).get_resource_string(
  934. self, resource_name
  935. )
  936. def resource_listdir(self, package_or_requirement, resource_name):
  937. """List the contents of the named resource directory"""
  938. return get_provider(package_or_requirement).resource_listdir(
  939. resource_name
  940. )
  941. def extraction_error(self):
  942. """Give an error message for problems extracting file(s)"""
  943. old_exc = sys.exc_info()[1]
  944. cache_path = self.extraction_path or get_default_cache()
  945. err = ExtractionError("""Can't extract file(s) to egg cache
  946. The following error occurred while trying to extract file(s) to the Python egg
  947. cache:
  948. %s
  949. The Python egg cache directory is currently set to:
  950. %s
  951. Perhaps your account does not have write access to this directory? You can
  952. change the cache directory by setting the PYTHON_EGG_CACHE environment
  953. variable to point to an accessible directory.
  954. """ % (old_exc, cache_path)
  955. )
  956. err.manager = self
  957. err.cache_path = cache_path
  958. err.original_error = old_exc
  959. raise err
  960. def get_cache_path(self, archive_name, names=()):
  961. """Return absolute location in cache for `archive_name` and `names`
  962. The parent directory of the resulting path will be created if it does
  963. not already exist. `archive_name` should be the base filename of the
  964. enclosing egg (which may not be the name of the enclosing zipfile!),
  965. including its ".egg" extension. `names`, if provided, should be a
  966. sequence of path name parts "under" the egg's extraction location.
  967. This method should only be called by resource providers that need to
  968. obtain an extraction location, and only for names they intend to
  969. extract, as it tracks the generated names for possible cleanup later.
  970. """
  971. extract_path = self.extraction_path or get_default_cache()
  972. target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
  973. try:
  974. _bypass_ensure_directory(target_path)
  975. except:
  976. self.extraction_error()
  977. self._warn_unsafe_extraction_path(extract_path)
  978. self.cached_files[target_path] = 1
  979. return target_path
  980. @staticmethod
  981. def _warn_unsafe_extraction_path(path):
  982. """
  983. If the default extraction path is overridden and set to an insecure
  984. location, such as /tmp, it opens up an opportunity for an attacker to
  985. replace an extracted file with an unauthorized payload. Warn the user
  986. if a known insecure location is used.
  987. See Distribute #375 for more details.
  988. """
  989. if os.name == 'nt' and not path.startswith(os.environ['windir']):
  990. # On Windows, permissions are generally restrictive by default
  991. # and temp directories are not writable by other users, so
  992. # bypass the warning.
  993. return
  994. mode = os.stat(path).st_mode
  995. if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
  996. msg = ("%s is writable by group/others and vulnerable to attack "
  997. "when "
  998. "used with get_resource_filename. Consider a more secure "
  999. "location (set with .set_extraction_path or the "
  1000. "PYTHON_EGG_CACHE environment variable)." % path)
  1001. warnings.warn(msg, UserWarning)
  1002. def postprocess(self, tempname, filename):
  1003. """Perform any platform-specific postprocessing of `tempname`
  1004. This is where Mac header rewrites should be done; other platforms don't
  1005. have anything special they should do.
  1006. Resource providers should call this method ONLY after successfully
  1007. extracting a compressed resource. They must NOT call it on resources
  1008. that are already in the filesystem.
  1009. `tempname` is the current (temporary) name of the file, and `filename`
  1010. is the name it will be renamed to by the caller after this routine
  1011. returns.
  1012. """
  1013. if os.name == 'posix':
  1014. # Make the resource executable
  1015. mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
  1016. os.chmod(tempname, mode)
  1017. def set_extraction_path(self, path):
  1018. """Set the base path where resources will be extracted to, if needed.
  1019. If you do not call this routine before any extractions take place, the
  1020. path defaults to the return value of ``get_default_cache()``. (Which
  1021. is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  1022. platform-specific fallbacks. See that routine's documentation for more
  1023. details.)
  1024. Resources are extracted to subdirectories of this path based upon
  1025. information given by the ``IResourceProvider``. You may set this to a
  1026. temporary directory, but then you must call ``cleanup_resources()`` to
  1027. delete the extracted files when done. There is no guarantee that
  1028. ``cleanup_resources()`` will be able to remove all extracted files.
  1029. (Note: you may not change the extraction path for a given resource
  1030. manager once resources have been extracted, unless you first call
  1031. ``cleanup_resources()``.)
  1032. """
  1033. if self.cached_files:
  1034. raise ValueError(
  1035. "Can't change extraction path, files already extracted"
  1036. )
  1037. self.extraction_path = path
  1038. def cleanup_resources(self, force=False):
  1039. """
  1040. Delete all extracted resource files and directories, returning a list
  1041. of the file and directory names that could not be successfully removed.
  1042. This function does not have any concurrency protection, so it should
  1043. generally only be called when the extraction path is a temporary
  1044. directory exclusive to a single process. This method is not
  1045. automatically called; you must call it explicitly or register it as an
  1046. ``atexit`` function if you wish to ensure cleanup of a temporary
  1047. directory used for extractions.
  1048. """
  1049. # XXX
  1050. def get_default_cache():
  1051. """Determine the default cache location
  1052. This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
  1053. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
  1054. "Application Data" directory. On all other systems, it's "~/.python-eggs".
  1055. """
  1056. try:
  1057. return os.environ['PYTHON_EGG_CACHE']
  1058. except KeyError:
  1059. pass
  1060. if os.name!='nt':
  1061. return os.path.expanduser('~/.python-eggs')
  1062. # XXX this may be locale-specific!
  1063. app_data = 'Application Data'
  1064. app_homes = [
  1065. # best option, should be locale-safe
  1066. (('APPDATA',), None),
  1067. (('USERPROFILE',), app_data),
  1068. (('HOMEDRIVE','HOMEPATH'), app_data),
  1069. (('HOMEPATH',), app_data),
  1070. (('HOME',), None),
  1071. # 95/98/ME
  1072. (('WINDIR',), app_data),
  1073. ]
  1074. for keys, subdir in app_homes:
  1075. dirname = ''
  1076. for key in keys:
  1077. if key in os.environ:
  1078. dirname = os.path.join(dirname, os.environ[key])
  1079. else:
  1080. break
  1081. else:
  1082. if subdir:
  1083. dirname = os.path.join(dirname, subdir)
  1084. return os.path.join(dirname, 'Python-Eggs')
  1085. else:
  1086. raise RuntimeError(
  1087. "Please set the PYTHON_EGG_CACHE enviroment variable"
  1088. )
  1089. def safe_name(name):
  1090. """Convert an arbitrary string to a standard distribution name
  1091. Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  1092. """
  1093. return re.sub('[^A-Za-z0-9.]+', '-', name)
  1094. def safe_version(version):
  1095. """
  1096. Convert an arbitrary string to a standard version string
  1097. """
  1098. try:
  1099. # normalize the version
  1100. return str(packaging.version.Version(version))
  1101. except packaging.version.InvalidVersion:
  1102. version = version.replace(' ','.')
  1103. return re.sub('[^A-Za-z0-9.]+', '-', version)
  1104. def safe_extra(extra):
  1105. """Convert an arbitrary string to a standard 'extra' name
  1106. Any runs of non-alphanumeric characters are replaced with a single '_',
  1107. and the result is always lowercased.
  1108. """
  1109. return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  1110. def to_filename(name):
  1111. """Convert a project or version name to its filename-escaped form
  1112. Any '-' characters are currently replaced with '_'.
  1113. """
  1114. return name.replace('-','_')
  1115. class MarkerEvaluation(object):
  1116. values = {
  1117. 'os_name': lambda: os.name,
  1118. 'sys_platform': lambda: sys.platform,
  1119. 'python_full_version': platform.python_version,
  1120. 'python_version': lambda: platform.python_version()[:3],
  1121. 'platform_version': platform.version,
  1122. 'platform_machine': platform.machine,
  1123. 'python_implementation': platform.python_implementation,
  1124. }
  1125. @classmethod
  1126. def is_invalid_marker(cls, text):
  1127. """
  1128. Validate text as a PEP 426 environment marker; return an exception
  1129. if invalid or False otherwise.
  1130. """
  1131. try:
  1132. cls.evaluate_marker(text)
  1133. except SyntaxError as e:
  1134. return cls.normalize_exception(e)
  1135. return False
  1136. @staticmethod
  1137. def normalize_exception(exc):
  1138. """
  1139. Given a SyntaxError from a marker evaluation, normalize the error
  1140. message:
  1141. - Remove indications of filename and line number.
  1142. - Replace platform-specific error messages with standard error
  1143. messages.
  1144. """
  1145. subs = {
  1146. 'unexpected EOF while parsing': 'invalid syntax',
  1147. 'parenthesis is never closed': 'invalid syntax',
  1148. }
  1149. exc.filename = None
  1150. exc.lineno = None