PageRenderTime 39ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/env/lib/python3.3/site-packages/pkg_resources.py

https://github.com/wantsomechocolate/MosaicMaker
Python | 3029 lines | 2984 code | 7 blank | 38 comment | 15 complexity | b308d2d3899d87b11968aee0308aa9f8 MD5 | raw file
  1. """Package resource API
  2. --------------------
  3. A resource is a logical file contained within a package, or a logical
  4. subdirectory thereof. The package resource API expects resource names
  5. to have their path parts separated with ``/``, *not* whatever the local
  6. path separator is. Do not use os.path operations to manipulate resource
  7. names being passed into the API.
  8. The package resource API is designed to work with normal filesystem packages,
  9. .egg files, and unpacked .egg files. It can also work in a limited way with
  10. .zip files and with custom PEP 302 loaders that support the ``get_data()``
  11. method.
  12. """
  13. import sys, os, time, re, imp, types, zipfile, zipimport
  14. import warnings
  15. import stat
  16. try:
  17. from urlparse import urlparse, urlunparse
  18. except ImportError:
  19. from urllib.parse import urlparse, urlunparse
  20. try:
  21. frozenset
  22. except NameError:
  23. from sets import ImmutableSet as frozenset
  24. try:
  25. basestring
  26. next = lambda o: o.next()
  27. from cStringIO import StringIO as BytesIO
  28. def exec_(code, globs=None, locs=None):
  29. if globs is None:
  30. frame = sys._getframe(1)
  31. globs = frame.f_globals
  32. if locs is None:
  33. locs = frame.f_locals
  34. del frame
  35. elif locs is None:
  36. locs = globs
  37. exec("""exec code in globs, locs""")
  38. except NameError:
  39. basestring = str
  40. from io import BytesIO
  41. exec_ = eval("exec")
  42. def execfile(fn, globs=None, locs=None):
  43. if globs is None:
  44. globs = globals()
  45. if locs is None:
  46. locs = globs
  47. exec_(compile(open(fn).read(), fn, 'exec'), globs, locs)
  48. import functools
  49. reduce = functools.reduce
  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. # Avoid try/except due to potential problems with delayed import mechanisms.
  61. if sys.version_info >= (3, 3) and sys.implementation.name == "cpython":
  62. import importlib._bootstrap as importlib_bootstrap
  63. else:
  64. importlib_bootstrap = None
  65. try:
  66. import parser
  67. except ImportError:
  68. pass
  69. def _bypass_ensure_directory(name, mode=0x1FF): # 0777
  70. # Sandbox-bypassing version of ensure_directory()
  71. if not WRITE_SUPPORT:
  72. raise IOError('"os.mkdir" not supported on this platform.')
  73. dirname, filename = split(name)
  74. if dirname and filename and not isdir(dirname):
  75. _bypass_ensure_directory(dirname)
  76. mkdir(dirname, mode)
  77. _state_vars = {}
  78. def _declare_state(vartype, **kw):
  79. g = globals()
  80. for name, val in kw.items():
  81. g[name] = val
  82. _state_vars[name] = vartype
  83. def __getstate__():
  84. state = {}
  85. g = globals()
  86. for k, v in _state_vars.items():
  87. state[k] = g['_sget_'+v](g[k])
  88. return state
  89. def __setstate__(state):
  90. g = globals()
  91. for k, v in state.items():
  92. g['_sset_'+_state_vars[k]](k, g[k], v)
  93. return state
  94. def _sget_dict(val):
  95. return val.copy()
  96. def _sset_dict(key, ob, state):
  97. ob.clear()
  98. ob.update(state)
  99. def _sget_object(val):
  100. return val.__getstate__()
  101. def _sset_object(key, ob, state):
  102. ob.__setstate__(state)
  103. _sget_none = _sset_none = lambda *args: None
  104. def get_supported_platform():
  105. """Return this platform's maximum compatible version.
  106. distutils.util.get_platform() normally reports the minimum version
  107. of Mac OS X that would be required to *use* extensions produced by
  108. distutils. But what we want when checking compatibility is to know the
  109. version of Mac OS X that we are *running*. To allow usage of packages that
  110. explicitly require a newer version of Mac OS X, we must also know the
  111. current version of the OS.
  112. If this condition occurs for any other platform with a version in its
  113. platform strings, this function should be extended accordingly.
  114. """
  115. plat = get_build_platform(); m = macosVersionString.match(plat)
  116. if m is not None and sys.platform == "darwin":
  117. try:
  118. plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
  119. except ValueError:
  120. pass # not Mac OS X
  121. return plat
  122. __all__ = [
  123. # Basic resource access and distribution/entry point discovery
  124. 'require', 'run_script', 'get_provider', 'get_distribution',
  125. 'load_entry_point', 'get_entry_map', 'get_entry_info', 'iter_entry_points',
  126. 'resource_string', 'resource_stream', 'resource_filename',
  127. 'resource_listdir', 'resource_exists', 'resource_isdir',
  128. # Environmental control
  129. 'declare_namespace', 'working_set', 'add_activation_listener',
  130. 'find_distributions', 'set_extraction_path', 'cleanup_resources',
  131. 'get_default_cache',
  132. # Primary implementation classes
  133. 'Environment', 'WorkingSet', 'ResourceManager',
  134. 'Distribution', 'Requirement', 'EntryPoint',
  135. # Exceptions
  136. 'ResolutionError','VersionConflict','DistributionNotFound','UnknownExtra',
  137. 'ExtractionError',
  138. # Parsing functions and string utilities
  139. 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
  140. 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
  141. 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',
  142. # filesystem utilities
  143. 'ensure_directory', 'normalize_path',
  144. # Distribution "precedence" constants
  145. 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
  146. # "Provider" interfaces, implementations, and registration/lookup APIs
  147. 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
  148. 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
  149. 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
  150. 'register_finder', 'register_namespace_handler', 'register_loader_type',
  151. 'fixup_namespace_packages', 'get_importer',
  152. # Deprecated/backward compatibility only
  153. 'run_main', 'AvailableDistributions',
  154. ]
  155. class ResolutionError(Exception):
  156. """Abstract base for dependency resolution errors"""
  157. def __repr__(self):
  158. return self.__class__.__name__+repr(self.args)
  159. class VersionConflict(ResolutionError):
  160. """An already-installed version conflicts with the requested version"""
  161. class DistributionNotFound(ResolutionError):
  162. """A requested distribution was not found"""
  163. class UnknownExtra(ResolutionError):
  164. """Distribution doesn't have an "extra feature" of the given name"""
  165. _provider_factories = {}
  166. PY_MAJOR = sys.version[:3]
  167. EGG_DIST = 3
  168. BINARY_DIST = 2
  169. SOURCE_DIST = 1
  170. CHECKOUT_DIST = 0
  171. DEVELOP_DIST = -1
  172. def register_loader_type(loader_type, provider_factory):
  173. """Register `provider_factory` to make providers for `loader_type`
  174. `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
  175. and `provider_factory` is a function that, passed a *module* object,
  176. returns an ``IResourceProvider`` for that module.
  177. """
  178. _provider_factories[loader_type] = provider_factory
  179. def get_provider(moduleOrReq):
  180. """Return an IResourceProvider for the named module or requirement"""
  181. if isinstance(moduleOrReq,Requirement):
  182. return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  183. try:
  184. module = sys.modules[moduleOrReq]
  185. except KeyError:
  186. __import__(moduleOrReq)
  187. module = sys.modules[moduleOrReq]
  188. loader = getattr(module, '__loader__', None)
  189. return _find_adapter(_provider_factories, loader)(module)
  190. def _macosx_vers(_cache=[]):
  191. if not _cache:
  192. import platform
  193. version = platform.mac_ver()[0]
  194. # fallback for MacPorts
  195. if version == '':
  196. import plistlib
  197. plist = '/System/Library/CoreServices/SystemVersion.plist'
  198. if os.path.exists(plist):
  199. if hasattr(plistlib, 'readPlist'):
  200. plist_content = plistlib.readPlist(plist)
  201. if 'ProductVersion' in plist_content:
  202. version = plist_content['ProductVersion']
  203. _cache.append(version.split('.'))
  204. return _cache[0]
  205. def _macosx_arch(machine):
  206. return {'PowerPC':'ppc', 'Power_Macintosh':'ppc'}.get(machine,machine)
  207. def get_build_platform():
  208. """Return this platform's string for platform-specific distributions
  209. XXX Currently this is the same as ``distutils.util.get_platform()``, but it
  210. needs some hacks for Linux and Mac OS X.
  211. """
  212. try:
  213. # Python 2.7 or >=3.2
  214. from sysconfig import get_platform
  215. except ImportError:
  216. from distutils.util import get_platform
  217. plat = get_platform()
  218. if sys.platform == "darwin" and not plat.startswith('macosx-'):
  219. try:
  220. version = _macosx_vers()
  221. machine = os.uname()[4].replace(" ", "_")
  222. return "macosx-%d.%d-%s" % (int(version[0]), int(version[1]),
  223. _macosx_arch(machine))
  224. except ValueError:
  225. # if someone is running a non-Mac darwin system, this will fall
  226. # through to the default implementation
  227. pass
  228. return plat
  229. macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
  230. darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
  231. get_platform = get_build_platform # XXX backward compat
  232. def compatible_platforms(provided,required):
  233. """Can code for the `provided` platform run on the `required` platform?
  234. Returns true if either platform is ``None``, or the platforms are equal.
  235. XXX Needs compatibility checks for Linux and other unixy OSes.
  236. """
  237. if provided is None or required is None or provided==required:
  238. return True # easy case
  239. # Mac OS X special cases
  240. reqMac = macosVersionString.match(required)
  241. if reqMac:
  242. provMac = macosVersionString.match(provided)
  243. # is this a Mac package?
  244. if not provMac:
  245. # this is backwards compatibility for packages built before
  246. # setuptools 0.6. All packages built after this point will
  247. # use the new macosx designation.
  248. provDarwin = darwinVersionString.match(provided)
  249. if provDarwin:
  250. dversion = int(provDarwin.group(1))
  251. macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
  252. if dversion == 7 and macosversion >= "10.3" or \
  253. dversion == 8 and macosversion >= "10.4":
  254. #import warnings
  255. #warnings.warn("Mac eggs should be rebuilt to "
  256. # "use the macosx designation instead of darwin.",
  257. # category=DeprecationWarning)
  258. return True
  259. return False # egg isn't macosx or legacy darwin
  260. # are they the same major version and machine type?
  261. if provMac.group(1) != reqMac.group(1) or \
  262. provMac.group(3) != reqMac.group(3):
  263. return False
  264. # is the required OS major update >= the provided one?
  265. if int(provMac.group(2)) > int(reqMac.group(2)):
  266. return False
  267. return True
  268. # XXX Linux and other platforms' special cases should go here
  269. return False
  270. def run_script(dist_spec, script_name):
  271. """Locate distribution `dist_spec` and run its `script_name` script"""
  272. ns = sys._getframe(1).f_globals
  273. name = ns['__name__']
  274. ns.clear()
  275. ns['__name__'] = name
  276. require(dist_spec)[0].run_script(script_name, ns)
  277. run_main = run_script # backward compatibility
  278. def get_distribution(dist):
  279. """Return a current distribution object for a Requirement or string"""
  280. if isinstance(dist,basestring): dist = Requirement.parse(dist)
  281. if isinstance(dist,Requirement): dist = get_provider(dist)
  282. if not isinstance(dist,Distribution):
  283. raise TypeError("Expected string, Requirement, or Distribution", dist)
  284. return dist
  285. def load_entry_point(dist, group, name):
  286. """Return `name` entry point of `group` for `dist` or raise ImportError"""
  287. return get_distribution(dist).load_entry_point(group, name)
  288. def get_entry_map(dist, group=None):
  289. """Return the entry point map for `group`, or the full entry map"""
  290. return get_distribution(dist).get_entry_map(group)
  291. def get_entry_info(dist, group, name):
  292. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  293. return get_distribution(dist).get_entry_info(group, name)
  294. class IMetadataProvider:
  295. def has_metadata(name):
  296. """Does the package's distribution contain the named metadata?"""
  297. def get_metadata(name):
  298. """The named metadata resource as a string"""
  299. def get_metadata_lines(name):
  300. """Yield named metadata resource as list of non-blank non-comment lines
  301. Leading and trailing whitespace is stripped from each line, and lines
  302. with ``#`` as the first non-blank character are omitted."""
  303. def metadata_isdir(name):
  304. """Is the named metadata a directory? (like ``os.path.isdir()``)"""
  305. def metadata_listdir(name):
  306. """List of metadata names in the directory (like ``os.listdir()``)"""
  307. def run_script(script_name, namespace):
  308. """Execute the named script in the supplied namespace dictionary"""
  309. class IResourceProvider(IMetadataProvider):
  310. """An object that provides access to package resources"""
  311. def get_resource_filename(manager, resource_name):
  312. """Return a true filesystem path for `resource_name`
  313. `manager` must be an ``IResourceManager``"""
  314. def get_resource_stream(manager, resource_name):
  315. """Return a readable file-like object for `resource_name`
  316. `manager` must be an ``IResourceManager``"""
  317. def get_resource_string(manager, resource_name):
  318. """Return a string containing the contents of `resource_name`
  319. `manager` must be an ``IResourceManager``"""
  320. def has_resource(resource_name):
  321. """Does the package contain the named resource?"""
  322. def resource_isdir(resource_name):
  323. """Is the named resource a directory? (like ``os.path.isdir()``)"""
  324. def resource_listdir(resource_name):
  325. """List of resource names in the directory (like ``os.listdir()``)"""
  326. class WorkingSet(object):
  327. """A collection of active distributions on sys.path (or a similar list)"""
  328. def __init__(self, entries=None):
  329. """Create working set from list of path entries (default=sys.path)"""
  330. self.entries = []
  331. self.entry_keys = {}
  332. self.by_key = {}
  333. self.callbacks = []
  334. if entries is None:
  335. entries = sys.path
  336. for entry in entries:
  337. self.add_entry(entry)
  338. def add_entry(self, entry):
  339. """Add a path item to ``.entries``, finding any distributions on it
  340. ``find_distributions(entry, True)`` is used to find distributions
  341. corresponding to the path entry, and they are added. `entry` is
  342. always appended to ``.entries``, even if it is already present.
  343. (This is because ``sys.path`` can contain the same value more than
  344. once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
  345. equal ``sys.path``.)
  346. """
  347. self.entry_keys.setdefault(entry, [])
  348. self.entries.append(entry)
  349. for dist in find_distributions(entry, True):
  350. self.add(dist, entry, False)
  351. def __contains__(self,dist):
  352. """True if `dist` is the active distribution for its project"""
  353. return self.by_key.get(dist.key) == dist
  354. def find(self, req):
  355. """Find a distribution matching requirement `req`
  356. If there is an active distribution for the requested project, this
  357. returns it as long as it meets the version requirement specified by
  358. `req`. But, if there is an active distribution for the project and it
  359. does *not* meet the `req` requirement, ``VersionConflict`` is raised.
  360. If there is no active distribution for the requested project, ``None``
  361. is returned.
  362. """
  363. dist = self.by_key.get(req.key)
  364. if dist is not None and dist not in req:
  365. raise VersionConflict(dist,req) # XXX add more info
  366. else:
  367. return dist
  368. def iter_entry_points(self, group, name=None):
  369. """Yield entry point objects from `group` matching `name`
  370. If `name` is None, yields all entry points in `group` from all
  371. distributions in the working set, otherwise only ones matching
  372. both `group` and `name` are yielded (in distribution order).
  373. """
  374. for dist in self:
  375. entries = dist.get_entry_map(group)
  376. if name is None:
  377. for ep in entries.values():
  378. yield ep
  379. elif name in entries:
  380. yield entries[name]
  381. def run_script(self, requires, script_name):
  382. """Locate distribution for `requires` and run `script_name` script"""
  383. ns = sys._getframe(1).f_globals
  384. name = ns['__name__']
  385. ns.clear()
  386. ns['__name__'] = name
  387. self.require(requires)[0].run_script(script_name, ns)
  388. def __iter__(self):
  389. """Yield distributions for non-duplicate projects in the working set
  390. The yield order is the order in which the items' path entries were
  391. added to the working set.
  392. """
  393. seen = {}
  394. for item in self.entries:
  395. if item not in self.entry_keys:
  396. # workaround a cache issue
  397. continue
  398. for key in self.entry_keys[item]:
  399. if key not in seen:
  400. seen[key]=1
  401. yield self.by_key[key]
  402. def add(self, dist, entry=None, insert=True):
  403. """Add `dist` to working set, associated with `entry`
  404. If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
  405. On exit from this routine, `entry` is added to the end of the working
  406. set's ``.entries`` (if it wasn't already present).
  407. `dist` is only added to the working set if it's for a project that
  408. doesn't already have a distribution in the set. If it's added, any
  409. callbacks registered with the ``subscribe()`` method will be called.
  410. """
  411. if insert:
  412. dist.insert_on(self.entries, entry)
  413. if entry is None:
  414. entry = dist.location
  415. keys = self.entry_keys.setdefault(entry,[])
  416. keys2 = self.entry_keys.setdefault(dist.location,[])
  417. if dist.key in self.by_key:
  418. return # ignore hidden distros
  419. self.by_key[dist.key] = dist
  420. if dist.key not in keys:
  421. keys.append(dist.key)
  422. if dist.key not in keys2:
  423. keys2.append(dist.key)
  424. self._added_new(dist)
  425. def resolve(self, requirements, env=None, installer=None):
  426. """List all distributions needed to (recursively) meet `requirements`
  427. `requirements` must be a sequence of ``Requirement`` objects. `env`,
  428. if supplied, should be an ``Environment`` instance. If
  429. not supplied, it defaults to all distributions available within any
  430. entry or distribution in the working set. `installer`, if supplied,
  431. will be invoked with each requirement that cannot be met by an
  432. already-installed distribution; it should return a ``Distribution`` or
  433. ``None``.
  434. """
  435. requirements = list(requirements)[::-1] # set up the stack
  436. processed = {} # set of processed requirements
  437. best = {} # key -> dist
  438. to_activate = []
  439. while requirements:
  440. req = requirements.pop(0) # process dependencies breadth-first
  441. if req in processed:
  442. # Ignore cyclic or redundant dependencies
  443. continue
  444. dist = best.get(req.key)
  445. if dist is None:
  446. # Find the best distribution and add it to the map
  447. dist = self.by_key.get(req.key)
  448. if dist is None:
  449. if env is None:
  450. env = Environment(self.entries)
  451. dist = best[req.key] = env.best_match(req, self, installer)
  452. if dist is None:
  453. #msg = ("The '%s' distribution was not found on this "
  454. # "system, and is required by this application.")
  455. #raise DistributionNotFound(msg % req)
  456. # unfortunately, zc.buildout uses a str(err)
  457. # to get the name of the distribution here..
  458. raise DistributionNotFound(req)
  459. to_activate.append(dist)
  460. if dist not in req:
  461. # Oops, the "best" so far conflicts with a dependency
  462. raise VersionConflict(dist,req) # XXX put more info here
  463. requirements.extend(dist.requires(req.extras)[::-1])
  464. processed[req] = True
  465. return to_activate # return list of distros to activate
  466. def find_plugins(self,
  467. plugin_env, full_env=None, installer=None, fallback=True
  468. ):
  469. """Find all activatable distributions in `plugin_env`
  470. Example usage::
  471. distributions, errors = working_set.find_plugins(
  472. Environment(plugin_dirlist)
  473. )
  474. map(working_set.add, distributions) # add plugins+libs to sys.path
  475. print 'Could not load', errors # display errors
  476. The `plugin_env` should be an ``Environment`` instance that contains
  477. only distributions that are in the project's "plugin directory" or
  478. directories. The `full_env`, if supplied, should be an ``Environment``
  479. contains all currently-available distributions. If `full_env` is not
  480. supplied, one is created automatically from the ``WorkingSet`` this
  481. method is called on, which will typically mean that every directory on
  482. ``sys.path`` will be scanned for distributions.
  483. `installer` is a standard installer callback as used by the
  484. ``resolve()`` method. The `fallback` flag indicates whether we should
  485. attempt to resolve older versions of a plugin if the newest version
  486. cannot be resolved.
  487. This method returns a 2-tuple: (`distributions`, `error_info`), where
  488. `distributions` is a list of the distributions found in `plugin_env`
  489. that were loadable, along with any other distributions that are needed
  490. to resolve their dependencies. `error_info` is a dictionary mapping
  491. unloadable plugin distributions to an exception instance describing the
  492. error that occurred. Usually this will be a ``DistributionNotFound`` or
  493. ``VersionConflict`` instance.
  494. """
  495. plugin_projects = list(plugin_env)
  496. plugin_projects.sort() # scan project names in alphabetic order
  497. error_info = {}
  498. distributions = {}
  499. if full_env is None:
  500. env = Environment(self.entries)
  501. env += plugin_env
  502. else:
  503. env = full_env + plugin_env
  504. shadow_set = self.__class__([])
  505. list(map(shadow_set.add, self)) # put all our entries in shadow_set
  506. for project_name in plugin_projects:
  507. for dist in plugin_env[project_name]:
  508. req = [dist.as_requirement()]
  509. try:
  510. resolvees = shadow_set.resolve(req, env, installer)
  511. except ResolutionError:
  512. v = sys.exc_info()[1]
  513. error_info[dist] = v # save error info
  514. if fallback:
  515. continue # try the next older version of project
  516. else:
  517. break # give up on this project, keep going
  518. else:
  519. list(map(shadow_set.add, resolvees))
  520. distributions.update(dict.fromkeys(resolvees))
  521. # success, no need to try any more versions of this project
  522. break
  523. distributions = list(distributions)
  524. distributions.sort()
  525. return distributions, error_info
  526. def require(self, *requirements):
  527. """Ensure that distributions matching `requirements` are activated
  528. `requirements` must be a string or a (possibly-nested) sequence
  529. thereof, specifying the distributions and versions required. The
  530. return value is a sequence of the distributions that needed to be
  531. activated to fulfill the requirements; all relevant distributions are
  532. included, even if they were already activated in this working set.
  533. """
  534. needed = self.resolve(parse_requirements(requirements))
  535. for dist in needed:
  536. self.add(dist)
  537. return needed
  538. def subscribe(self, callback):
  539. """Invoke `callback` for all distributions (including existing ones)"""
  540. if callback in self.callbacks:
  541. return
  542. self.callbacks.append(callback)
  543. for dist in self:
  544. callback(dist)
  545. def _added_new(self, dist):
  546. for callback in self.callbacks:
  547. callback(dist)
  548. def __getstate__(self):
  549. return (
  550. self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
  551. self.callbacks[:]
  552. )
  553. def __setstate__(self, e_k_b_c):
  554. entries, keys, by_key, callbacks = e_k_b_c
  555. self.entries = entries[:]
  556. self.entry_keys = keys.copy()
  557. self.by_key = by_key.copy()
  558. self.callbacks = callbacks[:]
  559. class Environment(object):
  560. """Searchable snapshot of distributions on a search path"""
  561. def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
  562. """Snapshot distributions available on a search path
  563. Any distributions found on `search_path` are added to the environment.
  564. `search_path` should be a sequence of ``sys.path`` items. If not
  565. supplied, ``sys.path`` is used.
  566. `platform` is an optional string specifying the name of the platform
  567. that platform-specific distributions must be compatible with. If
  568. unspecified, it defaults to the current platform. `python` is an
  569. optional string naming the desired version of Python (e.g. ``'2.4'``);
  570. it defaults to the current version.
  571. You may explicitly set `platform` (and/or `python`) to ``None`` if you
  572. wish to map *all* distributions, not just those compatible with the
  573. running platform or Python version.
  574. """
  575. self._distmap = {}
  576. self._cache = {}
  577. self.platform = platform
  578. self.python = python
  579. self.scan(search_path)
  580. def can_add(self, dist):
  581. """Is distribution `dist` acceptable for this environment?
  582. The distribution must match the platform and python version
  583. requirements specified when this environment was created, or False
  584. is returned.
  585. """
  586. return (self.python is None or dist.py_version is None
  587. or dist.py_version==self.python) \
  588. and compatible_platforms(dist.platform,self.platform)
  589. def remove(self, dist):
  590. """Remove `dist` from the environment"""
  591. self._distmap[dist.key].remove(dist)
  592. def scan(self, search_path=None):
  593. """Scan `search_path` for distributions usable in this environment
  594. Any distributions found are added to the environment.
  595. `search_path` should be a sequence of ``sys.path`` items. If not
  596. supplied, ``sys.path`` is used. Only distributions conforming to
  597. the platform/python version defined at initialization are added.
  598. """
  599. if search_path is None:
  600. search_path = sys.path
  601. for item in search_path:
  602. for dist in find_distributions(item):
  603. self.add(dist)
  604. def __getitem__(self,project_name):
  605. """Return a newest-to-oldest list of distributions for `project_name`
  606. """
  607. try:
  608. return self._cache[project_name]
  609. except KeyError:
  610. project_name = project_name.lower()
  611. if project_name not in self._distmap:
  612. return []
  613. if project_name not in self._cache:
  614. dists = self._cache[project_name] = self._distmap[project_name]
  615. _sort_dists(dists)
  616. return self._cache[project_name]
  617. def add(self,dist):
  618. """Add `dist` if we ``can_add()`` it and it isn't already added"""
  619. if self.can_add(dist) and dist.has_version():
  620. dists = self._distmap.setdefault(dist.key,[])
  621. if dist not in dists:
  622. dists.append(dist)
  623. if dist.key in self._cache:
  624. _sort_dists(self._cache[dist.key])
  625. def best_match(self, req, working_set, installer=None):
  626. """Find distribution best matching `req` and usable on `working_set`
  627. This calls the ``find(req)`` method of the `working_set` to see if a
  628. suitable distribution is already active. (This may raise
  629. ``VersionConflict`` if an unsuitable version of the project is already
  630. active in the specified `working_set`.) If a suitable distribution
  631. isn't active, this method returns the newest distribution in the
  632. environment that meets the ``Requirement`` in `req`. If no suitable
  633. distribution is found, and `installer` is supplied, then the result of
  634. calling the environment's ``obtain(req, installer)`` method will be
  635. returned.
  636. """
  637. dist = working_set.find(req)
  638. if dist is not None:
  639. return dist
  640. for dist in self[req.key]:
  641. if dist in req:
  642. return dist
  643. return self.obtain(req, installer) # try and download/install
  644. def obtain(self, requirement, installer=None):
  645. """Obtain a distribution matching `requirement` (e.g. via download)
  646. Obtain a distro that matches requirement (e.g. via download). In the
  647. base ``Environment`` class, this routine just returns
  648. ``installer(requirement)``, unless `installer` is None, in which case
  649. None is returned instead. This method is a hook that allows subclasses
  650. to attempt other ways of obtaining a distribution before falling back
  651. to the `installer` argument."""
  652. if installer is not None:
  653. return installer(requirement)
  654. def __iter__(self):
  655. """Yield the unique project names of the available distributions"""
  656. for key in self._distmap.keys():
  657. if self[key]: yield key
  658. def __iadd__(self, other):
  659. """In-place addition of a distribution or environment"""
  660. if isinstance(other,Distribution):
  661. self.add(other)
  662. elif isinstance(other,Environment):
  663. for project in other:
  664. for dist in other[project]:
  665. self.add(dist)
  666. else:
  667. raise TypeError("Can't add %r to environment" % (other,))
  668. return self
  669. def __add__(self, other):
  670. """Add an environment or distribution to an environment"""
  671. new = self.__class__([], platform=None, python=None)
  672. for env in self, other:
  673. new += env
  674. return new
  675. AvailableDistributions = Environment # XXX backward compatibility
  676. class ExtractionError(RuntimeError):
  677. """An error occurred extracting a resource
  678. The following attributes are available from instances of this exception:
  679. manager
  680. The resource manager that raised this exception
  681. cache_path
  682. The base directory for resource extraction
  683. original_error
  684. The exception instance that caused extraction to fail
  685. """
  686. class ResourceManager:
  687. """Manage resource extraction and packages"""
  688. extraction_path = None
  689. def __init__(self):
  690. self.cached_files = {}
  691. def resource_exists(self, package_or_requirement, resource_name):
  692. """Does the named resource exist?"""
  693. return get_provider(package_or_requirement).has_resource(resource_name)
  694. def resource_isdir(self, package_or_requirement, resource_name):
  695. """Is the named resource an existing directory?"""
  696. return get_provider(package_or_requirement).resource_isdir(
  697. resource_name
  698. )
  699. def resource_filename(self, package_or_requirement, resource_name):
  700. """Return a true filesystem path for specified resource"""
  701. return get_provider(package_or_requirement).get_resource_filename(
  702. self, resource_name
  703. )
  704. def resource_stream(self, package_or_requirement, resource_name):
  705. """Return a readable file-like object for specified resource"""
  706. return get_provider(package_or_requirement).get_resource_stream(
  707. self, resource_name
  708. )
  709. def resource_string(self, package_or_requirement, resource_name):
  710. """Return specified resource as a string"""
  711. return get_provider(package_or_requirement).get_resource_string(
  712. self, resource_name
  713. )
  714. def resource_listdir(self, package_or_requirement, resource_name):
  715. """List the contents of the named resource directory"""
  716. return get_provider(package_or_requirement).resource_listdir(
  717. resource_name
  718. )
  719. def extraction_error(self):
  720. """Give an error message for problems extracting file(s)"""
  721. old_exc = sys.exc_info()[1]
  722. cache_path = self.extraction_path or get_default_cache()
  723. err = ExtractionError("""Can't extract file(s) to egg cache
  724. The following error occurred while trying to extract file(s) to the Python egg
  725. cache:
  726. %s
  727. The Python egg cache directory is currently set to:
  728. %s
  729. Perhaps your account does not have write access to this directory? You can
  730. change the cache directory by setting the PYTHON_EGG_CACHE environment
  731. variable to point to an accessible directory.
  732. """ % (old_exc, cache_path)
  733. )
  734. err.manager = self
  735. err.cache_path = cache_path
  736. err.original_error = old_exc
  737. raise err
  738. def get_cache_path(self, archive_name, names=()):
  739. """Return absolute location in cache for `archive_name` and `names`
  740. The parent directory of the resulting path will be created if it does
  741. not already exist. `archive_name` should be the base filename of the
  742. enclosing egg (which may not be the name of the enclosing zipfile!),
  743. including its ".egg" extension. `names`, if provided, should be a
  744. sequence of path name parts "under" the egg's extraction location.
  745. This method should only be called by resource providers that need to
  746. obtain an extraction location, and only for names they intend to
  747. extract, as it tracks the generated names for possible cleanup later.
  748. """
  749. extract_path = self.extraction_path or get_default_cache()
  750. target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
  751. try:
  752. _bypass_ensure_directory(target_path)
  753. except:
  754. self.extraction_error()
  755. self._warn_unsafe_extraction_path(extract_path)
  756. self.cached_files[target_path] = 1
  757. return target_path
  758. @staticmethod
  759. def _warn_unsafe_extraction_path(path):
  760. """
  761. If the default extraction path is overridden and set to an insecure
  762. location, such as /tmp, it opens up an opportunity for an attacker to
  763. replace an extracted file with an unauthorized payload. Warn the user
  764. if a known insecure location is used.
  765. See Distribute #375 for more details.
  766. """
  767. if os.name == 'nt' and not path.startswith(os.environ['windir']):
  768. # On Windows, permissions are generally restrictive by default
  769. # and temp directories are not writable by other users, so
  770. # bypass the warning.
  771. return
  772. mode = os.stat(path).st_mode
  773. if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
  774. msg = ("%s is writable by group/others and vulnerable to attack "
  775. "when "
  776. "used with get_resource_filename. Consider a more secure "
  777. "location (set with .set_extraction_path or the "
  778. "PYTHON_EGG_CACHE environment variable)." % path)
  779. warnings.warn(msg, UserWarning)
  780. def postprocess(self, tempname, filename):
  781. """Perform any platform-specific postprocessing of `tempname`
  782. This is where Mac header rewrites should be done; other platforms don't
  783. have anything special they should do.
  784. Resource providers should call this method ONLY after successfully
  785. extracting a compressed resource. They must NOT call it on resources
  786. that are already in the filesystem.
  787. `tempname` is the current (temporary) name of the file, and `filename`
  788. is the name it will be renamed to by the caller after this routine
  789. returns.
  790. """
  791. if os.name == 'posix':
  792. # Make the resource executable
  793. mode = ((os.stat(tempname).st_mode) | 0x16D) & 0xFFF # 0555, 07777
  794. os.chmod(tempname, mode)
  795. def set_extraction_path(self, path):
  796. """Set the base path where resources will be extracted to, if needed.
  797. If you do not call this routine before any extractions take place, the
  798. path defaults to the return value of ``get_default_cache()``. (Which
  799. is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  800. platform-specific fallbacks. See that routine's documentation for more
  801. details.)
  802. Resources are extracted to subdirectories of this path based upon
  803. information given by the ``IResourceProvider``. You may set this to a
  804. temporary directory, but then you must call ``cleanup_resources()`` to
  805. delete the extracted files when done. There is no guarantee that
  806. ``cleanup_resources()`` will be able to remove all extracted files.
  807. (Note: you may not change the extraction path for a given resource
  808. manager once resources have been extracted, unless you first call
  809. ``cleanup_resources()``.)
  810. """
  811. if self.cached_files:
  812. raise ValueError(
  813. "Can't change extraction path, files already extracted"
  814. )
  815. self.extraction_path = path
  816. def cleanup_resources(self, force=False):
  817. """
  818. Delete all extracted resource files and directories, returning a list
  819. of the file and directory names that could not be successfully removed.
  820. This function does not have any concurrency protection, so it should
  821. generally only be called when the extraction path is a temporary
  822. directory exclusive to a single process. This method is not
  823. automatically called; you must call it explicitly or register it as an
  824. ``atexit`` function if you wish to ensure cleanup of a temporary
  825. directory used for extractions.
  826. """
  827. # XXX
  828. def get_default_cache():
  829. """Determine the default cache location
  830. This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
  831. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
  832. "Application Data" directory. On all other systems, it's "~/.python-eggs".
  833. """
  834. try:
  835. return os.environ['PYTHON_EGG_CACHE']
  836. except KeyError:
  837. pass
  838. if os.name!='nt':
  839. return os.path.expanduser('~/.python-eggs')
  840. app_data = 'Application Data' # XXX this may be locale-specific!
  841. app_homes = [
  842. (('APPDATA',), None), # best option, should be locale-safe
  843. (('USERPROFILE',), app_data),
  844. (('HOMEDRIVE','HOMEPATH'), app_data),
  845. (('HOMEPATH',), app_data),
  846. (('HOME',), None),
  847. (('WINDIR',), app_data), # 95/98/ME
  848. ]
  849. for keys, subdir in app_homes:
  850. dirname = ''
  851. for key in keys:
  852. if key in os.environ:
  853. dirname = os.path.join(dirname, os.environ[key])
  854. else:
  855. break
  856. else:
  857. if subdir:
  858. dirname = os.path.join(dirname,subdir)
  859. return os.path.join(dirname, 'Python-Eggs')
  860. else:
  861. raise RuntimeError(
  862. "Please set the PYTHON_EGG_CACHE enviroment variable"
  863. )
  864. def safe_name(name):
  865. """Convert an arbitrary string to a standard distribution name
  866. Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  867. """
  868. return re.sub('[^A-Za-z0-9.]+', '-', name)
  869. def safe_version(version):
  870. """Convert an arbitrary string to a standard version string
  871. Spaces become dots, and all other non-alphanumeric characters become
  872. dashes, with runs of multiple dashes condensed to a single dash.
  873. """
  874. version = version.replace(' ','.')
  875. return re.sub('[^A-Za-z0-9.]+', '-', version)
  876. def safe_extra(extra):
  877. """Convert an arbitrary string to a standard 'extra' name
  878. Any runs of non-alphanumeric characters are replaced with a single '_',
  879. and the result is always lowercased.
  880. """
  881. return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  882. def to_filename(name):
  883. """Convert a project or version name to its filename-escaped form
  884. Any '-' characters are currently replaced with '_'.
  885. """
  886. return name.replace('-','_')
  887. _marker_names = {
  888. 'os': ['name'], 'sys': ['platform'],
  889. 'platform': ['version','machine','python_implementation'],
  890. 'python_version': [], 'python_full_version': [], 'extra':[],
  891. }
  892. _marker_values = {
  893. 'os_name': lambda: os.name,
  894. 'sys_platform': lambda: sys.platform,
  895. 'python_full_version': lambda: sys.version.split()[0],
  896. 'python_version': lambda:'%s.%s' % (sys.version_info[0], sys.version_info[1]),
  897. 'platform_version': lambda: _platinfo('version'),
  898. 'platform_machine': lambda: _platinfo('machine'),
  899. 'python_implementation': lambda: _platinfo('python_implementation') or _pyimp(),
  900. }
  901. def _platinfo(attr):
  902. try:
  903. import platform
  904. except ImportError:
  905. return ''
  906. return getattr(platform, attr, lambda:'')()
  907. def _pyimp():
  908. if sys.platform=='cli':
  909. return 'IronPython'
  910. elif sys.platform.startswith('java'):
  911. return 'Jython'
  912. elif '__pypy__' in sys.builtin_module_names:
  913. return 'PyPy'
  914. else:
  915. return 'CPython'
  916. def invalid_marker(text):
  917. """Validate text as a PEP 426 environment marker; return exception or False"""
  918. try:
  919. evaluate_marker(text)
  920. except SyntaxError:
  921. return sys.exc_info()[1]
  922. return False
  923. def evaluate_marker(text, extra=None, _ops={}):
  924. """
  925. Evaluate a PEP 426 environment marker on CPython 2.4+.
  926. Return a boolean indicating the marker result in this environment.
  927. Raise SyntaxError if marker is invalid.
  928. This implementation uses the 'parser' module, which is not implemented on
  929. Jython and has been superseded by the 'ast' module in Python 2.6 and
  930. later.
  931. """
  932. if not _ops:
  933. from token import NAME, STRING
  934. import token, symbol, operator
  935. def and_test(nodelist):
  936. # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
  937. return reduce(operator.and_, [interpret(nodelist[i]) for i in range(1,len(nodelist),2)])
  938. def test(nodelist):
  939. # MUST NOT short-circuit evaluation, or invalid syntax can be skipped!
  940. return reduce(operator.or_, [interpret(nodelist[i]) for i in range(1,len(nodelist),2)])
  941. def atom(nodelist):
  942. t = nodelist[1][0]
  943. if t == token.LPAR:
  944. if nodelist[2][0] == token.RPAR:
  945. raise SyntaxError("Empty parentheses")
  946. return interpret(nodelist[2])
  947. raise SyntaxError("Language feature not supported in environment markers")
  948. def comparison(nodelist):
  949. if len(nodelist)>4:
  950. raise SyntaxError("Chained comparison not allowed in environment markers")
  951. comp = nodelist[2][1]
  952. cop = comp[1]
  953. if comp[0] == NAME:
  954. if len(nodelist[2]) == 3:
  955. if cop == 'not':
  956. cop = 'not in'
  957. else:
  958. cop = 'is not'
  959. try:
  960. cop = _ops[cop]
  961. except KeyError:
  962. raise SyntaxError(repr(cop)+" operator not allowed in environment markers")
  963. return cop(evaluate(nodelist[1]), evaluate(nodelist[3]))
  964. _ops.update({
  965. symbol.test: test, symbol.and_test: and_test, symbol.atom: atom,
  966. symbol.comparison: comparison, 'not in': lambda x,y: x not in y,
  967. 'in': lambda x,y: x in y, '==': operator.eq, '!=': operator.ne,
  968. })
  969. if hasattr(symbol,'or_test'):
  970. _ops[symbol.or_test] = test
  971. def interpret(nodelist):
  972. while len(nodelist)==2: nodelist = nodelist[1]
  973. try:
  974. op = _ops[nodelist[0]]
  975. except KeyError:
  976. raise SyntaxError("Comparison or logical expression expected")
  977. raise SyntaxError("Language feature not supported in environment markers: "+symbol.sym_name[nodelist[0]])
  978. return op(nodelist)
  979. def evaluate(nodelist):
  980. while len(nodelist)==2: nodelist = nodelist[1]
  981. kind = nodelist[0]
  982. name = nodelist[1]
  983. #while len(name)==2: name = name[1]
  984. if kind==NAME:
  985. try:
  986. op = _marker_values[name]
  987. except KeyError:
  988. raise SyntaxError("Unknown name %r" % name)
  989. return op()
  990. if kind==STRING:
  991. s = nodelist[1]
  992. if s[:1] not in "'\"" or s.startswith('"""') or s.startswith("'''") \
  993. or '\\' in s:
  994. raise SyntaxError(
  995. "Only plain strings allowed in environment markers")
  996. return s[1:-1]
  997. raise SyntaxError("Language feature not supported in environment markers")
  998. return interpret(parser.expr(text).totuple(1)[1])
  999. def _markerlib_evaluate(text):
  1000. """
  1001. Evaluate a PEP 426 environment marker using markerlib.
  1002. Return a boolean indicating the marker result in this environment.
  1003. Raise SyntaxError if marker is invalid.
  1004. """
  1005. import _markerlib
  1006. # markerlib implements Metadata 1.2 (PEP 345) environment markers.
  1007. # Translate the variables to Metadata 2.0 (PEP 426).
  1008. env = _markerlib.default_environment()
  1009. for key in env.keys():
  1010. new_key = key.replace('.', '_')
  1011. env[new_key] = env.pop(key)
  1012. try:
  1013. result = _markerlib.interpret(text, env)
  1014. except NameError:
  1015. e = sys.exc_info()[1]
  1016. raise SyntaxError(e.args[0])
  1017. return result
  1018. if 'parser' not in globals():
  1019. # fallback to less-complete _markerlib implementation if 'parser' module
  1020. # is not available.
  1021. evaluate_marker = _markerlib_evaluate
  1022. class NullProvider:
  1023. """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
  1024. egg_name = None
  1025. egg_info = None
  1026. loader = None
  1027. def __init__(self, module):
  1028. self.loader = getattr(module, '__loader__', None)
  1029. self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  1030. def get_resource_filename(self, manager, resource_name):
  1031. return self._fn(self.module_path, resource_name)
  1032. def get_resource_stream(self, manager, resource_name):
  1033. return BytesIO(self.get_resource_string(manager, resource_name))
  1034. def get_resource_string(self, manager, resource_name):
  1035. return self._get(self._fn(self.module_path, resource_name))
  1036. def has_resource(self, resource_name):
  1037. return self._has(self._fn(self.module_path, resource_name))
  1038. def has_metadata(self, name):
  1039. return self.egg_info and self._has(self._fn(self.egg_info,name))
  1040. if sys.version_info <= (3,):
  1041. def get_metadata(self, name):
  1042. if not self.egg_info:
  1043. return ""
  1044. return self._get(self._fn(self.egg_info,name))
  1045. else:
  1046. def get_metadata(self, name):
  1047. if not self.egg_info:
  1048. return ""
  1049. return self._get(self._fn(self.egg_info,name)).decode("utf-8")
  1050. def get_metadata_lines(self, name):
  1051. return yield_lines(self.get_metadata(name))
  1052. def resource_isdir(self,resource_name):
  1053. return self._isdir(self._fn(self.module_path, resource_name))
  1054. def metadata_isdir(self,name):
  1055. return self.egg_info and self._isdir(self._fn(self.egg_info,name))
  1056. def resource_listdir(self,resource_name):
  1057. return self._listdir(self._fn(self.module_path,resource_name))
  1058. def metadata_listdir(self,name):
  1059. if self.egg_info:
  1060. return self._listdir(self._fn(self.egg_info,name))
  1061. return []
  1062. def run_script(self,script_name,namespace):
  1063. script = 'scripts/'+script_name
  1064. if not self.has_metadata(script):
  1065. raise ResolutionError("No script named %r" % script_name)
  1066. script_text = self.get_metadata(script).replace('\r\n','\n')
  1067. script_text = script_text.replace('\r','\n')
  1068. script_filename = self._fn(self.egg_info,script)
  1069. namespace['__file__'] = script_filename
  1070. if os.path.exists(script_filename):
  1071. execfile(script_filename, namespace, namespace)
  1072. else:
  1073. from linecache import cache
  1074. cache[script_filename] = (
  1075. len(script_text), 0, script_text.split('\n'), script_filename
  1076. )
  1077. script_code = compile(script_text,script_filename,'exec')
  1078. exec_(script_code, namespace, namespace)
  1079. def _has(self, path):
  1080. raise NotImplementedError(
  1081. "Can't perform this operation for unregistered loader type"
  1082. )
  1083. def _isdir(self, path):
  1084. raise NotImplementedError(
  1085. "Can't perform this operation for unregistered loader type"
  1086. )
  1087. def _listdir(self, path):
  1088. raise NotImplementedError(
  1089. "Can't perform this operation for unregistered loader type"
  1090. )
  1091. def _fn(self, base, resource_name):
  1092. if resource_name:
  1093. return os.path.join(base, *resource_name.split('/'))
  1094. return base
  1095. def _get(self, path):
  1096. if hasattr(self.loader, 'get_data'):
  1097. return self.loader.get_data(path)
  1098. raise NotImplementedError(
  1099. "Can't perform this operation for loaders without 'get_data()'"
  1100. )
  1101. register_loader_type(object, NullProvider)
  1102. class EggProvider(NullProvider):
  1103. """Provider based on a virtual filesystem"""
  1104. def __init__(self,module):
  1105. NullProvider.__init__(self,module)
  1106. self._setup_prefix()
  1107. def _setup_prefix(self):
  1108. # we assume here that our metadata may be nested inside a "basket"
  1109. # of multiple eggs; that's why we use module_path instead of .archive
  1110. path = self.module_path
  1111. old = None
  1112. while path!=old:
  1113. if path.lower().endswith('.egg'):
  1114. self.egg_name = os.path.basename(path)
  1115. self.egg_info = os.path.join(path, 'EGG-INFO')
  1116. self.egg_root = path
  1117. break
  1118. old = path
  1119. path, base = os.path.split(path)
  1120. class DefaultProvider(EggProvider):
  1121. """Provides access to package resources in the filesystem"""
  1122. def _has(self, path):
  1123. return os.path.exists(path)
  1124. def _isdir(self,path):
  1125. return os.path.isdir(path)
  1126. def _listdir(self,path):
  1127. return os.listdir(path)
  1128. def get_resource_stream(self, manager, resource_name):
  1129. return open(self._fn(self.module_path, resource_name), 'rb')
  1130. def _get(self, path):
  1131. stream = open(path, 'rb')
  1132. try:
  1133. return stream.read()
  1134. finally:
  1135. stream.close()
  1136. register_loader_type(type(None), DefaultProvider)
  1137. if importlib_bootstrap is not None:
  1138. register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
  1139. class EmptyProvider(NullProvider):
  1140. """Provider that returns nothing for all requests"""
  1141. _isdir = _has = lambda self,path: False
  1142. _get = lambda self,path: ''
  1143. _listdir = lambda self,path: []
  1144. module_path = None
  1145. def __init__(self):
  1146. pass
  1147. empty_provider = EmptyProvider()
  1148. def build_zipmanifest(path):
  1149. """
  1150. This builds a similar dictionary to the zipimport directory
  1151. caches. However instead of tuples, ZipInfo objects are stored.
  1152. The translation of the tuple is as follows:
  1153. * [0] - zipinfo.filename on stock pythons this needs "/" --> os.sep
  1154. on pypy it is the same (one reason why distribute did work
  1155. in some cases on pypy and win32).
  1156. * [1] - zipinfo.compress_type
  1157. * [2] - zipinfo.compress_size
  1158. * [3] - zipinfo.file_size
  1159. * [4] - len(utf-8 encoding of filename) if zipinfo & 0x800
  1160. len(ascii encoding of filename) otherwise
  1161. * [5] - (zipinfo.date_time[0] - 1980) << 9 |
  1162. zipinfo.date_time[1] << 5 | zipinfo.date_time[2]
  1163. * [6] - (zipinfo.date_time[3] - 1980) << 11 |
  1164. zipinfo.date_time[4] << 5 | (zipinfo.date_time[5] // 2)
  1165. * [7] - zipinfo.CRC
  1166. """
  1167. zipinfo = dict()
  1168. zfile = zipfile.ZipFile(path)
  1169. #Got ZipFile has not __exit__ on python 3.1
  1170. try:
  1171. for zitem in zfile.namelist():
  1172. zpath = zitem.replace('/', os.sep)
  1173. zipinfo[zpath] = zfile.getinfo(zitem)
  1174. assert zipinfo[zpath] is not None
  1175. finally:
  1176. zfile.close()
  1177. return zipinfo
  1178. class ZipProvider(EggProvider):
  1179. """Resource support for zips and eggs"""
  1180. eagers = None
  1181. def __init__(self, module):
  1182. EggProvider.__init__(self,module)
  1183. self.zipinfo = build_zipmanifest(self.loader.archive)
  1184. self.zip_pre = self.loader.archive+os.sep
  1185. def _zipinfo_name(self, fspath):
  1186. # Convert a virtual filename (full path to file) into a zipfile subpath
  1187. # usable with the zipimport directory cache for our target archive
  1188. if fspath.startswith(self.zip_pre):
  1189. return fspath[len(self.zip_pre):]
  1190. raise AssertionError(
  1191. "%s is not a subpath of %s" % (fspath,self.zip_pre)
  1192. )
  1193. def _parts(self,zip_path):
  1194. # Convert a zipfile subpath into an egg-relative path part list
  1195. fspath = self.zip_pre+zip_path # pseudo-fs path
  1196. if fspath.startswith(self.egg_root+os.sep):
  1197. return fspath[len(self.egg_root)+1:].split(os.sep)
  1198. raise AssertionError(
  1199. "%s is not a subpath of %s" % (fspath,self.egg_root)
  1200. )
  1201. def get_resource_filename(self, manager, resource_name):
  1202. if not self.egg_name:
  1203. raise NotImplementedError(
  1204. "resource_filename() only supported for .egg, not .zip"
  1205. )
  1206. # no need to lock for extraction, since we use temp names
  1207. zip_path = self._resource_to_zip(resource_name)
  1208. eagers = self._get_eager_resources()
  1209. if '/'.join(self._parts(zip_path)) in eagers:
  1210. for name in eagers:
  1211. self._extract_resource(manager, self._eager_to_zip(name))
  1212. return self._extract_resource(manager, zip_path)
  1213. @staticmethod
  1214. def _get_date_and_size(zip_stat):
  1215. size = zip_stat.file_size
  1216. date_time = zip_stat.date_time + (0, 0, -1) # ymdhms+wday, yday, dst
  1217. #1980 offset already done
  1218. timestamp = time.mktime(date_time)
  1219. return timestamp, size
  1220. def _extract_resource(self, manager, zip_path):
  1221. if zip_path in self._index():
  1222. for name in self._index()[zip_path]:
  1223. last = self._extract_resource(
  1224. manager, os.path.join(zip_path, name)
  1225. )
  1226. return os.path.dirname(last) # return the extracted directory name
  1227. timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
  1228. if not WRITE_SUPPORT:
  1229. raise IOError('"os.rename" and "os.unlink" are not supported '
  1230. 'on this platform')
  1231. try:
  1232. real_path = manager.get_cache_path(
  1233. self.egg_name, self._parts(zip_path)
  1234. )
  1235. if self._is_current(real_path, zip_path):
  1236. return real_path
  1237. outf, tmpnam = _mkstemp(".$extract", dir=os.path.dirname(real_path))
  1238. os.write(outf, self.loader.get_data(zip_path))
  1239. os.close(outf)
  1240. utime(tmpnam, (timestamp,timestamp))
  1241. manager.postprocess(tmpnam, real_path)
  1242. try:
  1243. rename(tmpnam, real_path)
  1244. except os.error:
  1245. if os.path.isfile(real_path):
  1246. if self._is_current(real_path, zip_path):
  1247. # the file became current since it was checked above,
  1248. # so proceed.
  1249. return real_path
  1250. elif os.name=='nt': # Windows, del old file and retry
  1251. unlink(real_path)
  1252. rename(tmpnam, real_path)
  1253. return real_path
  1254. raise
  1255. except os.error:
  1256. manager.extraction_error() # report a user-friendly error
  1257. return real_path
  1258. def _is_current(self, file_path, zip_path):
  1259. """
  1260. Return True if the file_path is current for this zip_path
  1261. """
  1262. timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
  1263. if not os.path.isfile(file_path):
  1264. return False
  1265. stat = os.stat(file_path)
  1266. if stat.st_size!=size or stat.st_mtime!=timestamp:
  1267. return False
  1268. # check that the contents match
  1269. zip_contents = self.loader.get_data(zip_path)
  1270. f = open(file_path, 'rb')
  1271. file_contents = f.read()
  1272. f.close()
  1273. return zip_contents == file_contents
  1274. def _get_eager_resources(self):
  1275. if self.eagers is None:
  1276. eagers = []
  1277. for name in ('native_libs.txt', 'eager_resources.txt'):
  1278. if self.has_metadata(name):
  1279. eagers.extend(self.get_metadata_lines(name))
  1280. self.eagers = eagers
  1281. return self.eagers
  1282. def _index(self):
  1283. try:
  1284. return self._dirindex
  1285. except AttributeError:
  1286. ind = {}
  1287. for path in self.zipinfo:
  1288. parts = path.split(os.sep)
  1289. while parts:
  1290. parent = os.sep.join(parts[:-1])
  1291. if parent in ind:
  1292. ind[parent].append(parts[-1])
  1293. break
  1294. else:
  1295. ind[parent] = [parts.pop()]
  1296. self._dirindex = ind
  1297. return ind
  1298. def _has(self, fspath):
  1299. zip_path = self._zipinfo_name(fspath)
  1300. return zip_path in self.zipinfo or zip_path in self._index()
  1301. def _isdir(self,fspath):
  1302. return self._zipinfo_name(fspath) in self._index()
  1303. def _listdir(self,fspath):
  1304. return list(self._index().get(self._zipinfo_name(fspath), ()))
  1305. def _eager_to_zip(self,resource_name):
  1306. return self._zipinfo_name(self._fn(self.egg_root,resource_name))
  1307. def _resource_to_zip(self,resource_name):
  1308. return self._zipinfo_name(self._fn(self.module_path,resource_name))
  1309. register_loader_type(zipimport.zipimporter, ZipProvider)
  1310. class FileMetadata(EmptyProvider):
  1311. """Metadata handler for standalone PKG-INFO files
  1312. Usage::
  1313. metadata = FileMetadata("/path/to/PKG-INFO")
  1314. This provider rejects all data and metadata requests except for PKG-INFO,
  1315. which is treated as existing, and will be the contents of the file at
  1316. the provided location.
  1317. """
  1318. def __init__(self,path):
  1319. self.path = path
  1320. def has_metadata(self,name):
  1321. return name=='PKG-INFO'
  1322. def get_metadata(self,name):
  1323. if name=='PKG-INFO':
  1324. f = open(self.path,'rU')
  1325. metadata = f.read()
  1326. f.close()
  1327. return metadata
  1328. raise KeyError("No metadata except PKG-INFO is available")
  1329. def get_metadata_lines(self,name):
  1330. return yield_lines(self.get_metadata(name))
  1331. class PathMetadata(DefaultProvider):
  1332. """Metadata provider for egg directories
  1333. Usage::
  1334. # Development eggs:
  1335. egg_info = "/path/to/PackageName.egg-info"
  1336. base_dir = os.path.dirname(egg_info)
  1337. metadata = PathMetadata(base_dir, egg_info)
  1338. dist_name = os.path.splitext(os.path.basename(egg_info))[0]
  1339. dist = Distribution(basedir,project_name=dist_name,metadata=metadata)
  1340. # Unpacked egg directories:
  1341. egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
  1342. metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
  1343. dist = Distribution.from_filename(egg_path, metadata=metadata)
  1344. """
  1345. def __init__(self, path, egg_info):
  1346. self.module_path = path
  1347. self.egg_info = egg_info
  1348. class EggMetadata(ZipProvider):
  1349. """Metadata provider for .egg files"""
  1350. def __init__(self, importer):
  1351. """Create a metadata provider from a zipimporter"""
  1352. self.zipinfo = build_zipmanifest(importer.archive)
  1353. self.zip_pre = importer.archive+os.sep
  1354. self.loader = importer
  1355. if importer.prefix:
  1356. self.module_path = os.path.join(importer.archive, importer.prefix)
  1357. else:
  1358. self.module_path = importer.archive
  1359. self._setup_prefix()
  1360. class ImpWrapper:
  1361. """PEP 302 Importer that wraps Python's "normal" import algorithm"""
  1362. def __init__(self, path=None):
  1363. self.path = path
  1364. def find_module(self, fullname, path=None):
  1365. subname = fullname.split(".")[-1]
  1366. if subname != fullname and self.path is None:
  1367. return None
  1368. if self.path is None:
  1369. path = None
  1370. else:
  1371. path = [self.path]
  1372. try:
  1373. file, filename, etc = imp.find_module(subname, path)
  1374. except ImportError:
  1375. return None
  1376. return ImpLoader(file, filename, etc)
  1377. class ImpLoader:
  1378. """PEP 302 Loader that wraps Python's "normal" import algorithm"""
  1379. def __init__(self, file, filename, etc):
  1380. self.file = file
  1381. self.filename = filename
  1382. self.etc = etc
  1383. def load_module(self, fullname):
  1384. try:
  1385. mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  1386. finally:
  1387. if self.file: self.file.close()
  1388. # Note: we don't set __loader__ because we want the module to look
  1389. # normal; i.e. this is just a wrapper for standard import machinery
  1390. return mod
  1391. def get_importer(path_item):
  1392. """Retrieve a PEP 302 "importer" for the given path item
  1393. If there is no importer, this returns a wrapper around the builtin import
  1394. machinery. The returned importer is only cached if it was created by a
  1395. path hook.
  1396. """
  1397. try:
  1398. importer = sys.path_importer_cache[path_item]
  1399. except KeyError:
  1400. for hook in sys.path_hooks:
  1401. try:
  1402. importer = hook(path_item)
  1403. except ImportError:
  1404. pass
  1405. else:
  1406. break
  1407. else:
  1408. importer = None
  1409. sys.path_importer_cache.setdefault(path_item,importer)
  1410. if importer is None:
  1411. try:
  1412. importer = ImpWrapper(path_item)
  1413. except ImportError:
  1414. pass
  1415. return importer
  1416. try:
  1417. from pkgutil import get_importer, ImpImporter
  1418. except ImportError:
  1419. pass # Python 2.3 or 2.4, use our own implementation
  1420. else:
  1421. ImpWrapper = ImpImporter # Python 2.5, use pkgutil's implementation
  1422. del ImpLoader, ImpImporter
  1423. _declare_state('dict', _distribution_finders = {})
  1424. def register_finder(importer_type, distribution_finder):
  1425. """Register `distribution_finder` to find distributions in sys.path items
  1426. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1427. handler), and `distribution_finder` is a callable that, passed a path
  1428. item and the importer instance, yields ``Distribution`` instances found on
  1429. that path item. See ``pkg_resources.find_on_path`` for an example."""
  1430. _distribution_finders[importer_type] = distribution_finder
  1431. def find_distributions(path_item, only=False):
  1432. """Yield distributions accessible via `path_item`"""
  1433. importer = get_importer(path_item)
  1434. finder = _find_adapter(_distribution_finders, importer)
  1435. return finder(importer, path_item, only)
  1436. def find_in_zip(importer, path_item, only=False):
  1437. metadata = EggMetadata(importer)
  1438. if metadata.has_metadata('PKG-INFO'):
  1439. yield Distribution.from_filename(path_item, metadata=metadata)
  1440. if only:
  1441. return # don't yield nested distros
  1442. for subitem in metadata.resource_listdir('/'):
  1443. if subitem.endswith('.egg'):
  1444. subpath = os.path.join(path_item, subitem)
  1445. for dist in find_in_zip(zipimport.zipimporter(subpath), subpath):
  1446. yield dist
  1447. register_finder(zipimport.zipimporter, find_in_zip)
  1448. def find_nothing(importer, path_item, only=False):
  1449. return ()
  1450. register_finder(object,find_nothing)
  1451. def find_on_path(importer, path_item, only=False):
  1452. """Yield distributions accessible on a sys.path directory"""
  1453. path_item = _normalize_cached(path_item)
  1454. if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
  1455. if path_item.lower().endswith('.egg'):
  1456. # unpacked egg
  1457. yield Distribution.from_filename(
  1458. path_item, metadata=PathMetadata(
  1459. path_item, os.path.join(path_item,'EGG-INFO')
  1460. )
  1461. )
  1462. else:
  1463. # scan for .egg and .egg-info in directory
  1464. for entry in os.listdir(path_item):
  1465. lower = entry.lower()
  1466. if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
  1467. fullpath = os.path.join(path_item, entry)
  1468. if os.path.isdir(fullpath):
  1469. # egg-info directory, allow getting metadata
  1470. metadata = PathMetadata(path_item, fullpath)
  1471. else:
  1472. metadata = FileMetadata(fullpath)
  1473. yield Distribution.from_location(
  1474. path_item,entry,metadata,precedence=DEVELOP_DIST
  1475. )
  1476. elif not only and lower.endswith('.egg'):
  1477. for dist in find_distributions(os.path.join(path_item, entry)):
  1478. yield dist
  1479. elif not only and lower.endswith('.egg-link'):
  1480. entry_file = open(os.path.join(path_item, entry))
  1481. try:
  1482. entry_lines = entry_file.readlines()
  1483. finally:
  1484. entry_file.close()
  1485. for line in entry_lines:
  1486. if not line.strip(): continue
  1487. for item in find_distributions(os.path.join(path_item,line.rstrip())):
  1488. yield item
  1489. break
  1490. register_finder(ImpWrapper,find_on_path)
  1491. if importlib_bootstrap is not None:
  1492. register_finder(importlib_bootstrap.FileFinder, find_on_path)
  1493. _declare_state('dict', _namespace_handlers={})
  1494. _declare_state('dict', _namespace_packages={})
  1495. def register_namespace_handler(importer_type, namespace_handler):
  1496. """Register `namespace_handler` to declare namespace packages
  1497. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1498. handler), and `namespace_handler` is a callable like this::
  1499. def namespace_handler(importer,path_entry,moduleName,module):
  1500. # return a path_entry to use for child packages
  1501. Namespace handlers are only called if the importer object has already
  1502. agreed that it can handle the relevant path item, and they should only
  1503. return a subpath if the module __path__ does not already contain an
  1504. equivalent subpath. For an example namespace handler, see
  1505. ``pkg_resources.file_ns_handler``.
  1506. """
  1507. _namespace_handlers[importer_type] = namespace_handler
  1508. def _handle_ns(packageName, path_item):
  1509. """Ensure that named package includes a subpath of path_item (if needed)"""
  1510. importer = get_importer(path_item)
  1511. if importer is None:
  1512. return None
  1513. loader = importer.find_module(packageName)
  1514. if loader is None:
  1515. return None
  1516. module = sys.modules.get(packageName)
  1517. if module is None:
  1518. module = sys.modules[packageName] = imp.new_module(packageName)
  1519. module.__path__ = []; _set_parent_ns(packageName)
  1520. elif not hasattr(module,'__path__'):
  1521. raise TypeError("Not a package:", packageName)
  1522. handler = _find_adapter(_namespace_handlers, importer)
  1523. subpath = handler(importer,path_item,packageName,module)
  1524. if subpath is not None:
  1525. path = module.__path__; path.append(subpath)
  1526. loader.load_module(packageName); module.__path__ = path
  1527. return subpath
  1528. def declare_namespace(packageName):
  1529. """Declare that package 'packageName' is a namespace package"""
  1530. imp.acquire_lock()
  1531. try:
  1532. if packageName in _namespace_packages:
  1533. return
  1534. path, parent = sys.path, None
  1535. if '.' in packageName:
  1536. parent = '.'.join(packageName.split('.')[:-1])
  1537. declare_namespace(parent)
  1538. if parent not in _namespace_packages:
  1539. __import__(parent)
  1540. try:
  1541. path = sys.modules[parent].__path__
  1542. except AttributeError:
  1543. raise TypeError("Not a package:", parent)
  1544. # Track what packages are namespaces, so when new path items are added,
  1545. # they can be updated
  1546. _namespace_packages.setdefault(parent,[]).append(packageName)
  1547. _namespace_packages.setdefault(packageName,[])
  1548. for path_item in path:
  1549. # Ensure all the parent's path items are reflected in the child,
  1550. # if they apply
  1551. _handle_ns(packageName, path_item)
  1552. finally:
  1553. imp.release_lock()
  1554. def fixup_namespace_packages(path_item, parent=None):
  1555. """Ensure that previously-declared namespace packages include path_item"""
  1556. imp.acquire_lock()
  1557. try:
  1558. for package in _namespace_packages.get(parent,()):
  1559. subpath = _handle_ns(package, path_item)
  1560. if subpath: fixup_namespace_packages(subpath,package)
  1561. finally:
  1562. imp.release_lock()
  1563. def file_ns_handler(importer, path_item, packageName, module):
  1564. """Compute an ns-package subpath for a filesystem or zipfile importer"""
  1565. subpath = os.path.join(path_item, packageName.split('.')[-1])
  1566. normalized = _normalize_cached(subpath)
  1567. for item in module.__path__:
  1568. if _normalize_cached(item)==normalized:
  1569. break
  1570. else:
  1571. # Only return the path if it's not already there
  1572. return subpath
  1573. register_namespace_handler(ImpWrapper,file_ns_handler)
  1574. register_namespace_handler(zipimport.zipimporter,file_ns_handler)
  1575. if importlib_bootstrap is not None:
  1576. register_namespace_handler(importlib_bootstrap.FileFinder, file_ns_handler)
  1577. def null_ns_handler(importer, path_item, packageName, module):
  1578. return None
  1579. register_namespace_handler(object,null_ns_handler)
  1580. def normalize_path(filename):
  1581. """Normalize a file/dir name for comparison purposes"""
  1582. return os.path.normcase(os.path.realpath(filename))
  1583. def _normalize_cached(filename,_cache={}):
  1584. try:
  1585. return _cache[filename]
  1586. except KeyError:
  1587. _cache[filename] = result = normalize_path(filename)
  1588. return result
  1589. def _set_parent_ns(packageName):
  1590. parts = packageName.split('.')
  1591. name = parts.pop()
  1592. if parts:
  1593. parent = '.'.join(parts)
  1594. setattr(sys.modules[parent], name, sys.modules[packageName])
  1595. def yield_lines(strs):
  1596. """Yield non-empty/non-comment lines of a ``basestring`` or sequence"""
  1597. if isinstance(strs,basestring):
  1598. for s in strs.splitlines():
  1599. s = s.strip()
  1600. if s and not s.startswith('#'): # skip blank lines/comments
  1601. yield s
  1602. else:
  1603. for ss in strs:
  1604. for s in yield_lines(ss):
  1605. yield s
  1606. LINE_END = re.compile(r"\s*(#.*)?$").match # whitespace and comment
  1607. CONTINUE = re.compile(r"\s*\\\s*(#.*)?$").match # line continuation
  1608. DISTRO = re.compile(r"\s*((\w|[-.])+)").match # Distribution or extra
  1609. VERSION = re.compile(r"\s*(<=?|>=?|==|!=)\s*((\w|[-.])+)").match # ver. info
  1610. COMMA = re.compile(r"\s*,").match # comma between items
  1611. OBRACKET = re.compile(r"\s*\[").match
  1612. CBRACKET = re.compile(r"\s*\]").match
  1613. MODULE = re.compile(r"\w+(\.\w+)*$").match
  1614. EGG_NAME = re.compile(
  1615. r"(?P<name>[^-]+)"
  1616. r"( -(?P<ver>[^-]+) (-py(?P<pyver>[^-]+) (-(?P<plat>.+))? )? )?",
  1617. re.VERBOSE | re.IGNORECASE
  1618. ).match
  1619. component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
  1620. replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
  1621. def _parse_version_parts(s):
  1622. for part in component_re.split(s):
  1623. part = replace(part,part)
  1624. if not part or part=='.':
  1625. continue
  1626. if part[:1] in '0123456789':
  1627. yield part.zfill(8) # pad for numeric comparison
  1628. else:
  1629. yield '*'+part
  1630. yield '*final' # ensure that alpha/beta/candidate are before final
  1631. def parse_version(s):
  1632. """Convert a version string to a chronologically-sortable key
  1633. This is a rough cross between distutils' StrictVersion and LooseVersion;
  1634. if you give it versions that would work with StrictVersion, then it behaves
  1635. the same; otherwise it acts like a slightly-smarter LooseVersion. It is
  1636. *possible* to create pathological version coding schemes that will fool
  1637. this parser, but they should be very rare in practice.
  1638. The returned value will be a tuple of strings. Numeric portions of the
  1639. version are padded to 8 digits so they will compare numerically, but
  1640. without relying on how numbers compare relative to strings. Dots are
  1641. dropped, but dashes are retained. Trailing zeros between alpha segments
  1642. or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
  1643. "2.4". Alphanumeric parts are lower-cased.
  1644. The algorithm assumes that strings like "-" and any alpha string that
  1645. alphabetically follows "final" represents a "patch level". So, "2.4-1"
  1646. is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
  1647. considered newer than "2.4-1", which in turn is newer than "2.4".
  1648. Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
  1649. come before "final" alphabetically) are assumed to be pre-release versions,
  1650. so that the version "2.4" is considered newer than "2.4a1".
  1651. Finally, to handle miscellaneous cases, the strings "pre", "preview", and
  1652. "rc" are treated as if they were "c", i.e. as though they were release
  1653. candidates, and therefore are not as new as a version string that does not
  1654. contain them, and "dev" is replaced with an '@' so that it sorts lower than
  1655. than any other pre-release tag.
  1656. """
  1657. parts = []
  1658. for part in _parse_version_parts(s.lower()):
  1659. if part.startswith('*'):
  1660. if part<'*final': # remove '-' before a prerelease tag
  1661. while parts and parts[-1]=='*final-': parts.pop()
  1662. # remove trailing zeros from each series of numeric parts
  1663. while parts and parts[-1]=='00000000':
  1664. parts.pop()
  1665. parts.append(part)
  1666. return tuple(parts)
  1667. class EntryPoint(object):
  1668. """Object representing an advertised importable object"""
  1669. def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
  1670. if not MODULE(module_name):
  1671. raise ValueError("Invalid module name", module_name)
  1672. self.name = name
  1673. self.module_name = module_name
  1674. self.attrs = tuple(attrs)
  1675. self.extras = Requirement.parse(("x[%s]" % ','.join(extras))).extras
  1676. self.dist = dist
  1677. def __str__(self):
  1678. s = "%s = %s" % (self.name, self.module_name)
  1679. if self.attrs:
  1680. s += ':' + '.'.join(self.attrs)
  1681. if self.extras:
  1682. s += ' [%s]' % ','.join(self.extras)
  1683. return s
  1684. def __repr__(self):
  1685. return "EntryPoint.parse(%r)" % str(self)
  1686. def load(self, require=True, env=None, installer=None):
  1687. if require: self.require(env, installer)
  1688. entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  1689. for attr in self.attrs:
  1690. try:
  1691. entry = getattr(entry,attr)
  1692. except AttributeError:
  1693. raise ImportError("%r has no %r attribute" % (entry,attr))
  1694. return entry
  1695. def require(self, env=None, installer=None):
  1696. if self.extras and not self.dist:
  1697. raise UnknownExtra("Can't require() without a distribution", self)
  1698. list(map(working_set.add,
  1699. working_set.resolve(self.dist.requires(self.extras),env,installer)))
  1700. #@classmethod
  1701. def parse(cls, src, dist=None):
  1702. """Parse a single entry point from string `src`
  1703. Entry point syntax follows the form::
  1704. name = some.module:some.attr [extra1,extra2]
  1705. The entry name and module name are required, but the ``:attrs`` and
  1706. ``[extras]`` parts are optional
  1707. """
  1708. try:
  1709. attrs = extras = ()
  1710. name,value = src.split('=',1)
  1711. if '[' in value:
  1712. value,extras = value.split('[',1)
  1713. req = Requirement.parse("x["+extras)
  1714. if req.specs: raise ValueError
  1715. extras = req.extras
  1716. if ':' in value:
  1717. value,attrs = value.split(':',1)
  1718. if not MODULE(attrs.rstrip()):
  1719. raise ValueError
  1720. attrs = attrs.rstrip().split('.')
  1721. except ValueError:
  1722. raise ValueError(
  1723. "EntryPoint must be in 'name=module:attrs [extras]' format",
  1724. src
  1725. )
  1726. else:
  1727. return cls(name.strip(), value.strip(), attrs, extras, dist)
  1728. parse = classmethod(parse)
  1729. #@classmethod
  1730. def parse_group(cls, group, lines, dist=None):
  1731. """Parse an entry point group"""
  1732. if not MODULE(group):
  1733. raise ValueError("Invalid group name", group)
  1734. this = {}
  1735. for line in yield_lines(lines):
  1736. ep = cls.parse(line, dist)
  1737. if ep.name in this:
  1738. raise ValueError("Duplicate entry point", group, ep.name)
  1739. this[ep.name]=ep
  1740. return this
  1741. parse_group = classmethod(parse_group)
  1742. #@classmethod
  1743. def parse_map(cls, data, dist=None):
  1744. """Parse a map of entry point groups"""
  1745. if isinstance(data,dict):
  1746. data = data.items()
  1747. else:
  1748. data = split_sections(data)
  1749. maps = {}
  1750. for group, lines in data:
  1751. if group is None:
  1752. if not lines:
  1753. continue
  1754. raise ValueError("Entry points must be listed in groups")
  1755. group = group.strip()
  1756. if group in maps:
  1757. raise ValueError("Duplicate group name", group)
  1758. maps[group] = cls.parse_group(group, lines, dist)
  1759. return maps
  1760. parse_map = classmethod(parse_map)
  1761. def _remove_md5_fragment(location):
  1762. if not location:
  1763. return ''
  1764. parsed = urlparse(location)
  1765. if parsed[-1].startswith('md5='):
  1766. return urlunparse(parsed[:-1] + ('',))
  1767. return location
  1768. class Distribution(object):
  1769. """Wrap an actual or potential sys.path entry w/metadata"""
  1770. PKG_INFO = 'PKG-INFO'
  1771. def __init__(self,
  1772. location=None, metadata=None, project_name=None, version=None,
  1773. py_version=PY_MAJOR, platform=None, precedence = EGG_DIST
  1774. ):
  1775. self.project_name = safe_name(project_name or 'Unknown')
  1776. if version is not None:
  1777. self._version = safe_version(version)
  1778. self.py_version = py_version
  1779. self.platform = platform
  1780. self.location = location
  1781. self.precedence = precedence
  1782. self._provider = metadata or empty_provider
  1783. #@classmethod
  1784. def from_location(cls,location,basename,metadata=None,**kw):
  1785. project_name, version, py_version, platform = [None]*4
  1786. basename, ext = os.path.splitext(basename)
  1787. if ext.lower() in _distributionImpl:
  1788. # .dist-info gets much metadata differently
  1789. match = EGG_NAME(basename)
  1790. if match:
  1791. project_name, version, py_version, platform = match.group(
  1792. 'name','ver','pyver','plat'
  1793. )
  1794. cls = _distributionImpl[ext.lower()]
  1795. return cls(
  1796. location, metadata, project_name=project_name, version=version,
  1797. py_version=py_version, platform=platform, **kw
  1798. )
  1799. from_location = classmethod(from_location)
  1800. hashcmp = property(
  1801. lambda self: (
  1802. getattr(self,'parsed_version',()),
  1803. self.precedence,
  1804. self.key,
  1805. _remove_md5_fragment(self.location),
  1806. self.py_version,
  1807. self.platform
  1808. )
  1809. )
  1810. def __hash__(self): return hash(self.hashcmp)
  1811. def __lt__(self, other):
  1812. return self.hashcmp < other.hashcmp
  1813. def __le__(self, other):
  1814. return self.hashcmp <= other.hashcmp
  1815. def __gt__(self, other):
  1816. return self.hashcmp > other.hashcmp
  1817. def __ge__(self, other):
  1818. return self.hashcmp >= other.hashcmp
  1819. def __eq__(self, other):
  1820. if not isinstance(other, self.__class__):
  1821. # It's not a Distribution, so they are not equal
  1822. return False
  1823. return self.hashcmp == other.hashcmp
  1824. def __ne__(self, other):
  1825. return not self == other
  1826. # These properties have to be lazy so that we don't have to load any
  1827. # metadata until/unless it's actually needed. (i.e., some distributions
  1828. # may not know their name or version without loading PKG-INFO)
  1829. #@property
  1830. def key(self):
  1831. try:
  1832. return self._key
  1833. except AttributeError:
  1834. self._key = key = self.project_name.lower()
  1835. return key
  1836. key = property(key)
  1837. #@property
  1838. def parsed_version(self):
  1839. try:
  1840. return self._parsed_version
  1841. except AttributeError:
  1842. self._parsed_version = pv = parse_version(self.version)
  1843. return pv
  1844. parsed_version = property(parsed_version)
  1845. #@property
  1846. def version(self):
  1847. try:
  1848. return self._version
  1849. except AttributeError:
  1850. for line in self._get_metadata(self.PKG_INFO):
  1851. if line.lower().startswith('version:'):
  1852. self._version = safe_version(line.split(':',1)[1].strip())
  1853. return self._version
  1854. else:
  1855. raise ValueError(
  1856. "Missing 'Version:' header and/or %s file" % self.PKG_INFO, self
  1857. )
  1858. version = property(version)
  1859. #@property
  1860. def _dep_map(self):
  1861. try:
  1862. return self.__dep_map
  1863. except AttributeError:
  1864. dm = self.__dep_map = {None: []}
  1865. for name in 'requires.txt', 'depends.txt':
  1866. for extra,reqs in split_sections(self._get_metadata(name)):
  1867. if extra:
  1868. if ':' in extra:
  1869. extra, marker = extra.split(':',1)
  1870. if invalid_marker(marker):
  1871. reqs=[] # XXX warn
  1872. elif not evaluate_marker(marker):
  1873. reqs=[]
  1874. extra = safe_extra(extra) or None
  1875. dm.setdefault(extra,[]).extend(parse_requirements(reqs))
  1876. return dm
  1877. _dep_map = property(_dep_map)
  1878. def requires(self,extras=()):
  1879. """List of Requirements needed for this distro if `extras` are used"""
  1880. dm = self._dep_map
  1881. deps = []
  1882. deps.extend(dm.get(None,()))
  1883. for ext in extras:
  1884. try:
  1885. deps.extend(dm[safe_extra(ext)])
  1886. except KeyError:
  1887. raise UnknownExtra(
  1888. "%s has no such extra feature %r" % (self, ext)
  1889. )
  1890. return deps
  1891. def _get_metadata(self,name):
  1892. if self.has_metadata(name):
  1893. for line in self.get_metadata_lines(name):
  1894. yield line
  1895. def activate(self,path=None):
  1896. """Ensure distribution is importable on `path` (default=sys.path)"""
  1897. if path is None: path = sys.path
  1898. self.insert_on(path)
  1899. if path is sys.path:
  1900. fixup_namespace_packages(self.location)
  1901. list(map(declare_namespace, self._get_metadata('namespace_packages.txt')))
  1902. def egg_name(self):
  1903. """Return what this distribution's standard .egg filename should be"""
  1904. filename = "%s-%s-py%s" % (
  1905. to_filename(self.project_name), to_filename(self.version),
  1906. self.py_version or PY_MAJOR
  1907. )
  1908. if self.platform:
  1909. filename += '-'+self.platform
  1910. return filename
  1911. def __repr__(self):
  1912. if self.location:
  1913. return "%s (%s)" % (self,self.location)
  1914. else:
  1915. return str(self)
  1916. def __str__(self):
  1917. try: version = getattr(self,'version',None)
  1918. except ValueError: version = None
  1919. version = version or "[unknown version]"
  1920. return "%s %s" % (self.project_name,version)
  1921. def __getattr__(self,attr):
  1922. """Delegate all unrecognized public attributes to .metadata provider"""
  1923. if attr.startswith('_'):
  1924. raise AttributeError(attr)
  1925. return getattr(self._provider, attr)
  1926. #@classmethod
  1927. def from_filename(cls,filename,metadata=None, **kw):
  1928. return cls.from_location(
  1929. _normalize_cached(filename), os.path.basename(filename), metadata,
  1930. **kw
  1931. )
  1932. from_filename = classmethod(from_filename)
  1933. def as_requirement(self):
  1934. """Return a ``Requirement`` that matches this distribution exactly"""
  1935. return Requirement.parse('%s==%s' % (self.project_name, self.version))
  1936. def load_entry_point(self, group, name):
  1937. """Return the `name` entry point of `group` or raise ImportError"""
  1938. ep = self.get_entry_info(group,name)
  1939. if ep is None:
  1940. raise ImportError("Entry point %r not found" % ((group,name),))
  1941. return ep.load()
  1942. def get_entry_map(self, group=None):
  1943. """Return the entry point map for `group`, or the full entry map"""
  1944. try:
  1945. ep_map = self._ep_map
  1946. except AttributeError:
  1947. ep_map = self._ep_map = EntryPoint.parse_map(
  1948. self._get_metadata('entry_points.txt'), self
  1949. )
  1950. if group is not None:
  1951. return ep_map.get(group,{})
  1952. return ep_map
  1953. def get_entry_info(self, group, name):
  1954. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  1955. return self.get_entry_map(group).get(name)
  1956. def insert_on(self, path, loc = None):
  1957. """Insert self.location in path before its nearest parent directory"""
  1958. loc = loc or self.location
  1959. if not loc:
  1960. return
  1961. nloc = _normalize_cached(loc)
  1962. bdir = os.path.dirname(nloc)
  1963. npath= [(p and _normalize_cached(p) or p) for p in path]
  1964. bp = None
  1965. for p, item in enumerate(npath):
  1966. if item==nloc:
  1967. break
  1968. elif item==bdir and self.precedence==EGG_DIST:
  1969. # if it's an .egg, give it precedence over its directory
  1970. if path is sys.path:
  1971. self.check_version_conflict()
  1972. path.insert(p, loc)
  1973. npath.insert(p, nloc)
  1974. break
  1975. else:
  1976. if path is sys.path:
  1977. self.check_version_conflict()
  1978. path.append(loc)
  1979. return
  1980. # p is the spot where we found or inserted loc; now remove duplicates
  1981. while 1:
  1982. try:
  1983. np = npath.index(nloc, p+1)
  1984. except ValueError:
  1985. break
  1986. else:
  1987. del npath[np], path[np]
  1988. p = np # ha!
  1989. return
  1990. def check_version_conflict(self):
  1991. if self.key=='setuptools':
  1992. return # ignore the inevitable setuptools self-conflicts :(
  1993. nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
  1994. loc = normalize_path(self.location)
  1995. for modname in self._get_metadata('top_level.txt'):
  1996. if (modname not in sys.modules or modname in nsp
  1997. or modname in _namespace_packages
  1998. ):
  1999. continue
  2000. if modname in ('pkg_resources', 'setuptools', 'site'):
  2001. continue
  2002. fn = getattr(sys.modules[modname], '__file__', None)
  2003. if fn and (normalize_path(fn).startswith(loc) or
  2004. fn.startswith(self.location)):
  2005. continue
  2006. issue_warning(
  2007. "Module %s was already imported from %s, but %s is being added"
  2008. " to sys.path" % (modname, fn, self.location),
  2009. )
  2010. def has_version(self):
  2011. try:
  2012. self.version
  2013. except ValueError:
  2014. issue_warning("Unbuilt egg for "+repr(self))
  2015. return False
  2016. return True
  2017. def clone(self,**kw):
  2018. """Copy this distribution, substituting in any changed keyword args"""
  2019. for attr in (
  2020. 'project_name', 'version', 'py_version', 'platform', 'location',
  2021. 'precedence'
  2022. ):
  2023. kw.setdefault(attr, getattr(self,attr,None))
  2024. kw.setdefault('metadata', self._provider)
  2025. return self.__class__(**kw)
  2026. #@property
  2027. def extras(self):
  2028. return [dep for dep in self._dep_map if dep]
  2029. extras = property(extras)
  2030. class DistInfoDistribution(Distribution):
  2031. """Wrap an actual or potential sys.path entry w/metadata, .dist-info style"""
  2032. PKG_INFO = 'METADATA'
  2033. EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
  2034. @property
  2035. def _parsed_pkg_info(self):
  2036. """Parse and cache metadata"""
  2037. try:
  2038. return self._pkg_info
  2039. except AttributeError:
  2040. from email.parser import Parser
  2041. self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
  2042. return self._pkg_info
  2043. @property
  2044. def _dep_map(self):
  2045. try:
  2046. return self.__dep_map
  2047. except AttributeError:
  2048. self.__dep_map = self._compute_dependencies()
  2049. return self.__dep_map
  2050. def _preparse_requirement(self, requires_dist):
  2051. """Convert 'Foobar (1); baz' to ('Foobar ==1', 'baz')
  2052. Split environment marker, add == prefix to version specifiers as
  2053. necessary, and remove parenthesis.
  2054. """
  2055. parts = requires_dist.split(';', 1) + ['']
  2056. distvers = parts[0].strip()
  2057. mark = parts[1].strip()
  2058. distvers = re.sub(self.EQEQ, r"\1==\2\3", distvers)
  2059. distvers = distvers.replace('(', '').replace(')', '')
  2060. return (distvers, mark)
  2061. def _compute_dependencies(self):
  2062. """Recompute this distribution's dependencies."""
  2063. from _markerlib import compile as compile_marker
  2064. dm = self.__dep_map = {None: []}
  2065. reqs = []
  2066. # Including any condition expressions
  2067. for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
  2068. distvers, mark = self._preparse_requirement(req)
  2069. parsed = next(parse_requirements(distvers))
  2070. parsed.marker_fn = compile_marker(mark)
  2071. reqs.append(parsed)
  2072. def reqs_for_extra(extra):
  2073. for req in reqs:
  2074. if req.marker_fn(override={'extra':extra}):
  2075. yield req
  2076. common = frozenset(reqs_for_extra(None))
  2077. dm[None].extend(common)
  2078. for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
  2079. extra = safe_extra(extra.strip())
  2080. dm[extra] = list(frozenset(reqs_for_extra(extra)) - common)
  2081. return dm
  2082. _distributionImpl = {'.egg': Distribution,
  2083. '.egg-info': Distribution,
  2084. '.dist-info': DistInfoDistribution }
  2085. def issue_warning(*args,**kw):
  2086. level = 1
  2087. g = globals()
  2088. try:
  2089. # find the first stack frame that is *not* code in
  2090. # the pkg_resources module, to use for the warning
  2091. while sys._getframe(level).f_globals is g:
  2092. level += 1
  2093. except ValueError:
  2094. pass
  2095. from warnings import warn
  2096. warn(stacklevel = level+1, *args, **kw)
  2097. def parse_requirements(strs):
  2098. """Yield ``Requirement`` objects for each specification in `strs`
  2099. `strs` must be an instance of ``basestring``, or a (possibly-nested)
  2100. iterable thereof.
  2101. """
  2102. # create a steppable iterator, so we can handle \-continuations
  2103. lines = iter(yield_lines(strs))
  2104. def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):
  2105. items = []
  2106. while not TERMINATOR(line,p):
  2107. if CONTINUE(line,p):
  2108. try:
  2109. line = next(lines); p = 0
  2110. except StopIteration:
  2111. raise ValueError(
  2112. "\\ must not appear on the last nonblank line"
  2113. )
  2114. match = ITEM(line,p)
  2115. if not match:
  2116. raise ValueError("Expected "+item_name+" in",line,"at",line[p:])
  2117. items.append(match.group(*groups))
  2118. p = match.end()
  2119. match = COMMA(line,p)
  2120. if match:
  2121. p = match.end() # skip the comma
  2122. elif not TERMINATOR(line,p):
  2123. raise ValueError(
  2124. "Expected ',' or end-of-list in",line,"at",line[p:]
  2125. )
  2126. match = TERMINATOR(line,p)
  2127. if match: p = match.end() # skip the terminator, if any
  2128. return line, p, items
  2129. for line in lines:
  2130. match = DISTRO(line)
  2131. if not match:
  2132. raise ValueError("Missing distribution spec", line)
  2133. project_name = match.group(1)
  2134. p = match.end()
  2135. extras = []
  2136. match = OBRACKET(line,p)
  2137. if match:
  2138. p = match.end()
  2139. line, p, extras = scan_list(
  2140. DISTRO, CBRACKET, line, p, (1,), "'extra' name"
  2141. )
  2142. line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec")
  2143. specs = [(op,safe_version(val)) for op,val in specs]
  2144. yield Requirement(project_name, specs, extras)
  2145. def _sort_dists(dists):
  2146. tmp = [(dist.hashcmp,dist) for dist in dists]
  2147. tmp.sort()
  2148. dists[::-1] = [d for hc,d in tmp]
  2149. class Requirement:
  2150. def __init__(self, project_name, specs, extras):
  2151. """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
  2152. self.unsafe_name, project_name = project_name, safe_name(project_name)
  2153. self.project_name, self.key = project_name, project_name.lower()
  2154. index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]
  2155. index.sort()
  2156. self.specs = [(op,ver) for parsed,trans,op,ver in index]
  2157. self.index, self.extras = index, tuple(map(safe_extra,extras))
  2158. self.hashCmp = (
  2159. self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),
  2160. frozenset(self.extras)
  2161. )
  2162. self.__hash = hash(self.hashCmp)
  2163. def __str__(self):
  2164. specs = ','.join([''.join(s) for s in self.specs])
  2165. extras = ','.join(self.extras)
  2166. if extras: extras = '[%s]' % extras
  2167. return '%s%s%s' % (self.project_name, extras, specs)
  2168. def __eq__(self,other):
  2169. return isinstance(other,Requirement) and self.hashCmp==other.hashCmp
  2170. def __contains__(self,item):
  2171. if isinstance(item,Distribution):
  2172. if item.key != self.key: return False
  2173. if self.index: item = item.parsed_version # only get if we need it
  2174. elif isinstance(item,basestring):
  2175. item = parse_version(item)
  2176. last = None
  2177. compare = lambda a, b: (a > b) - (a < b) # -1, 0, 1
  2178. for parsed,trans,op,ver in self.index:
  2179. action = trans[compare(item,parsed)] # Indexing: 0, 1, -1
  2180. if action=='F': return False
  2181. elif action=='T': return True
  2182. elif action=='+': last = True
  2183. elif action=='-' or last is None: last = False
  2184. if last is None: last = True # no rules encountered
  2185. return last
  2186. def __hash__(self):
  2187. return self.__hash
  2188. def __repr__(self): return "Requirement.parse(%r)" % str(self)
  2189. #@staticmethod
  2190. def parse(s):
  2191. reqs = list(parse_requirements(s))
  2192. if reqs:
  2193. if len(reqs)==1:
  2194. return reqs[0]
  2195. raise ValueError("Expected only one requirement", s)
  2196. raise ValueError("No requirements found", s)
  2197. parse = staticmethod(parse)
  2198. state_machine = {
  2199. # =><
  2200. '<' : '--T',
  2201. '<=': 'T-T',
  2202. '>' : 'F+F',
  2203. '>=': 'T+F',
  2204. '==': 'T..',
  2205. '!=': 'F++',
  2206. }
  2207. def _get_mro(cls):
  2208. """Get an mro for a type or classic class"""
  2209. if not isinstance(cls,type):
  2210. class cls(cls,object): pass
  2211. return cls.__mro__[1:]
  2212. return cls.__mro__
  2213. def _find_adapter(registry, ob):
  2214. """Return an adapter factory for `ob` from `registry`"""
  2215. for t in _get_mro(getattr(ob, '__class__', type(ob))):
  2216. if t in registry:
  2217. return registry[t]
  2218. def ensure_directory(path):
  2219. """Ensure that the parent directory of `path` exists"""
  2220. dirname = os.path.dirname(path)
  2221. if not os.path.isdir(dirname):
  2222. os.makedirs(dirname)
  2223. def split_sections(s):
  2224. """Split a string or iterable thereof into (section,content) pairs
  2225. Each ``section`` is a stripped version of the section header ("[section]")
  2226. and each ``content`` is a list of stripped lines excluding blank lines and
  2227. comment-only lines. If there are any such lines before the first section
  2228. header, they're returned in a first ``section`` of ``None``.
  2229. """
  2230. section = None
  2231. content = []
  2232. for line in yield_lines(s):
  2233. if line.startswith("["):
  2234. if line.endswith("]"):
  2235. if section or content:
  2236. yield section, content
  2237. section = line[1:-1].strip()
  2238. content = []
  2239. else:
  2240. raise ValueError("Invalid section heading", line)
  2241. else:
  2242. content.append(line)
  2243. # wrap up last segment
  2244. yield section, content
  2245. def _mkstemp(*args,**kw):
  2246. from tempfile import mkstemp
  2247. old_open = os.open
  2248. try:
  2249. os.open = os_open # temporarily bypass sandboxing
  2250. return mkstemp(*args,**kw)
  2251. finally:
  2252. os.open = old_open # and then put it back
  2253. # Set up global resource manager (deliberately not state-saved)
  2254. _manager = ResourceManager()
  2255. def _initialize(g):
  2256. for name in dir(_manager):
  2257. if not name.startswith('_'):
  2258. g[name] = getattr(_manager, name)
  2259. _initialize(globals())
  2260. # Prepare the master working set and make the ``require()`` API available
  2261. _declare_state('object', working_set = WorkingSet())
  2262. try:
  2263. # Does the main program list any requirements?
  2264. from __main__ import __requires__
  2265. except ImportError:
  2266. pass # No: just use the default working set based on sys.path
  2267. else:
  2268. # Yes: ensure the requirements are met, by prefixing sys.path if necessary
  2269. try:
  2270. working_set.require(__requires__)
  2271. except VersionConflict: # try it without defaults already on sys.path
  2272. working_set = WorkingSet([]) # by starting with an empty path
  2273. for dist in working_set.resolve(
  2274. parse_requirements(__requires__), Environment()
  2275. ):
  2276. working_set.add(dist)
  2277. for entry in sys.path: # add any missing entries from sys.path
  2278. if entry not in working_set.entries:
  2279. working_set.add_entry(entry)
  2280. sys.path[:] = working_set.entries # then copy back to sys.path
  2281. require = working_set.require
  2282. iter_entry_points = working_set.iter_entry_points
  2283. add_activation_listener = working_set.subscribe
  2284. run_script = working_set.run_script
  2285. run_main = run_script # backward compatibility
  2286. # Activate all distributions already on sys.path, and ensure that
  2287. # all distributions added to the working set in the future (e.g. by
  2288. # calling ``require()``) will get activated as well.
  2289. add_activation_listener(lambda dist: dist.activate())
  2290. working_set.entries=[]; list(map(working_set.add_entry,sys.path)) # match order