PageRenderTime 68ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/pkg_resources.py

https://bitbucket.org/mumak/distribute
Python | 2837 lines | 2689 code | 86 blank | 62 comment | 60 complexity | 83849f8acfccefa57fdd5949e2405c32 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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, zipimport, time, re, imp, types
  14. from urlparse import urlparse, urlunparse
  15. try:
  16. frozenset
  17. except NameError:
  18. from sets import ImmutableSet as frozenset
  19. # capture these to bypass sandboxing
  20. from os import utime
  21. try:
  22. from os import mkdir, rename, unlink
  23. WRITE_SUPPORT = True
  24. except ImportError:
  25. # no write support, probably under GAE
  26. WRITE_SUPPORT = False
  27. from os import open as os_open
  28. from os.path import isdir, split
  29. # This marker is used to simplify the process that checks is the
  30. # setuptools package was installed by the Setuptools project
  31. # or by the Distribute project, in case Setuptools creates
  32. # a distribution with the same version.
  33. #
  34. # The bootstrapping script for instance, will check if this
  35. # attribute is present to decide wether to reinstall the package
  36. _distribute = True
  37. def _bypass_ensure_directory(name, mode=0777):
  38. # Sandbox-bypassing version of ensure_directory()
  39. if not WRITE_SUPPORT:
  40. raise IOError('"os.mkdir" not supported on this platform.')
  41. dirname, filename = split(name)
  42. if dirname and filename and not isdir(dirname):
  43. _bypass_ensure_directory(dirname)
  44. mkdir(dirname, mode)
  45. _state_vars = {}
  46. def _declare_state(vartype, **kw):
  47. g = globals()
  48. for name, val in kw.iteritems():
  49. g[name] = val
  50. _state_vars[name] = vartype
  51. def __getstate__():
  52. state = {}
  53. g = globals()
  54. for k, v in _state_vars.iteritems():
  55. state[k] = g['_sget_'+v](g[k])
  56. return state
  57. def __setstate__(state):
  58. g = globals()
  59. for k, v in state.iteritems():
  60. g['_sset_'+_state_vars[k]](k, g[k], v)
  61. return state
  62. def _sget_dict(val):
  63. return val.copy()
  64. def _sset_dict(key, ob, state):
  65. ob.clear()
  66. ob.update(state)
  67. def _sget_object(val):
  68. return val.__getstate__()
  69. def _sset_object(key, ob, state):
  70. ob.__setstate__(state)
  71. _sget_none = _sset_none = lambda *args: None
  72. def get_supported_platform():
  73. """Return this platform's maximum compatible version.
  74. distutils.util.get_platform() normally reports the minimum version
  75. of Mac OS X that would be required to *use* extensions produced by
  76. distutils. But what we want when checking compatibility is to know the
  77. version of Mac OS X that we are *running*. To allow usage of packages that
  78. explicitly require a newer version of Mac OS X, we must also know the
  79. current version of the OS.
  80. If this condition occurs for any other platform with a version in its
  81. platform strings, this function should be extended accordingly.
  82. """
  83. plat = get_build_platform(); m = macosVersionString.match(plat)
  84. if m is not None and sys.platform == "darwin":
  85. try:
  86. plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
  87. except ValueError:
  88. pass # not Mac OS X
  89. return plat
  90. __all__ = [
  91. # Basic resource access and distribution/entry point discovery
  92. 'require', 'run_script', 'get_provider', 'get_distribution',
  93. 'load_entry_point', 'get_entry_map', 'get_entry_info', 'iter_entry_points',
  94. 'resource_string', 'resource_stream', 'resource_filename',
  95. 'resource_listdir', 'resource_exists', 'resource_isdir',
  96. # Environmental control
  97. 'declare_namespace', 'working_set', 'add_activation_listener',
  98. 'find_distributions', 'set_extraction_path', 'cleanup_resources',
  99. 'get_default_cache',
  100. # Primary implementation classes
  101. 'Environment', 'WorkingSet', 'ResourceManager',
  102. 'Distribution', 'Requirement', 'EntryPoint',
  103. # Exceptions
  104. 'ResolutionError','VersionConflict','DistributionNotFound','UnknownExtra',
  105. 'ExtractionError',
  106. # Parsing functions and string utilities
  107. 'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
  108. 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
  109. 'safe_extra', 'to_filename',
  110. # filesystem utilities
  111. 'ensure_directory', 'normalize_path',
  112. # Distribution "precedence" constants
  113. 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
  114. # "Provider" interfaces, implementations, and registration/lookup APIs
  115. 'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
  116. 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
  117. 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
  118. 'register_finder', 'register_namespace_handler', 'register_loader_type',
  119. 'fixup_namespace_packages', 'get_importer',
  120. # Deprecated/backward compatibility only
  121. 'run_main', 'AvailableDistributions',
  122. ]
  123. class ResolutionError(Exception):
  124. """Abstract base for dependency resolution errors"""
  125. def __repr__(self):
  126. return self.__class__.__name__+repr(self.args)
  127. class VersionConflict(ResolutionError):
  128. """An already-installed version conflicts with the requested version"""
  129. class DistributionNotFound(ResolutionError):
  130. """A requested distribution was not found"""
  131. class UnknownExtra(ResolutionError):
  132. """Distribution doesn't have an "extra feature" of the given name"""
  133. _provider_factories = {}
  134. PY_MAJOR = sys.version[:3]
  135. EGG_DIST = 3
  136. BINARY_DIST = 2
  137. SOURCE_DIST = 1
  138. CHECKOUT_DIST = 0
  139. DEVELOP_DIST = -1
  140. def register_loader_type(loader_type, provider_factory):
  141. """Register `provider_factory` to make providers for `loader_type`
  142. `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
  143. and `provider_factory` is a function that, passed a *module* object,
  144. returns an ``IResourceProvider`` for that module.
  145. """
  146. _provider_factories[loader_type] = provider_factory
  147. def get_provider(moduleOrReq):
  148. """Return an IResourceProvider for the named module or requirement"""
  149. if isinstance(moduleOrReq,Requirement):
  150. return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  151. try:
  152. module = sys.modules[moduleOrReq]
  153. except KeyError:
  154. __import__(moduleOrReq)
  155. module = sys.modules[moduleOrReq]
  156. loader = getattr(module, '__loader__', None)
  157. return _find_adapter(_provider_factories, loader)(module)
  158. def _macosx_vers(_cache=[]):
  159. if not _cache:
  160. import platform
  161. version = platform.mac_ver()[0]
  162. # fallback for MacPorts
  163. if version == '':
  164. import plistlib
  165. plist = '/System/Library/CoreServices/SystemVersion.plist'
  166. if os.path.exists(plist):
  167. if hasattr(plistlib, 'readPlist'):
  168. plist_content = plistlib.readPlist(plist)
  169. if 'ProductVersion' in plist_content:
  170. version = plist_content['ProductVersion']
  171. _cache.append(version.split('.'))
  172. return _cache[0]
  173. def _macosx_arch(machine):
  174. return {'PowerPC':'ppc', 'Power_Macintosh':'ppc'}.get(machine,machine)
  175. def get_build_platform():
  176. """Return this platform's string for platform-specific distributions
  177. XXX Currently this is the same as ``distutils.util.get_platform()``, but it
  178. needs some hacks for Linux and Mac OS X.
  179. """
  180. try:
  181. from distutils.util import get_platform
  182. except ImportError:
  183. from sysconfig import get_platform
  184. plat = get_platform()
  185. if sys.platform == "darwin" and not plat.startswith('macosx-'):
  186. try:
  187. version = _macosx_vers()
  188. machine = os.uname()[4].replace(" ", "_")
  189. return "macosx-%d.%d-%s" % (int(version[0]), int(version[1]),
  190. _macosx_arch(machine))
  191. except ValueError:
  192. # if someone is running a non-Mac darwin system, this will fall
  193. # through to the default implementation
  194. pass
  195. return plat
  196. macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
  197. darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
  198. get_platform = get_build_platform # XXX backward compat
  199. def compatible_platforms(provided,required):
  200. """Can code for the `provided` platform run on the `required` platform?
  201. Returns true if either platform is ``None``, or the platforms are equal.
  202. XXX Needs compatibility checks for Linux and other unixy OSes.
  203. """
  204. if provided is None or required is None or provided==required:
  205. return True # easy case
  206. # Mac OS X special cases
  207. reqMac = macosVersionString.match(required)
  208. if reqMac:
  209. provMac = macosVersionString.match(provided)
  210. # is this a Mac package?
  211. if not provMac:
  212. # this is backwards compatibility for packages built before
  213. # setuptools 0.6. All packages built after this point will
  214. # use the new macosx designation.
  215. provDarwin = darwinVersionString.match(provided)
  216. if provDarwin:
  217. dversion = int(provDarwin.group(1))
  218. macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
  219. if dversion == 7 and macosversion >= "10.3" or \
  220. dversion == 8 and macosversion >= "10.4":
  221. #import warnings
  222. #warnings.warn("Mac eggs should be rebuilt to "
  223. # "use the macosx designation instead of darwin.",
  224. # category=DeprecationWarning)
  225. return True
  226. return False # egg isn't macosx or legacy darwin
  227. # are they the same major version and machine type?
  228. if provMac.group(1) != reqMac.group(1) or \
  229. provMac.group(3) != reqMac.group(3):
  230. return False
  231. # is the required OS major update >= the provided one?
  232. if int(provMac.group(2)) > int(reqMac.group(2)):
  233. return False
  234. return True
  235. # XXX Linux and other platforms' special cases should go here
  236. return False
  237. def run_script(dist_spec, script_name):
  238. """Locate distribution `dist_spec` and run its `script_name` script"""
  239. ns = sys._getframe(1).f_globals
  240. name = ns['__name__']
  241. ns.clear()
  242. ns['__name__'] = name
  243. require(dist_spec)[0].run_script(script_name, ns)
  244. run_main = run_script # backward compatibility
  245. def get_distribution(dist):
  246. """Return a current distribution object for a Requirement or string"""
  247. if isinstance(dist,basestring): dist = Requirement.parse(dist)
  248. if isinstance(dist,Requirement): dist = get_provider(dist)
  249. if not isinstance(dist,Distribution):
  250. raise TypeError("Expected string, Requirement, or Distribution", dist)
  251. return dist
  252. def load_entry_point(dist, group, name):
  253. """Return `name` entry point of `group` for `dist` or raise ImportError"""
  254. return get_distribution(dist).load_entry_point(group, name)
  255. def get_entry_map(dist, group=None):
  256. """Return the entry point map for `group`, or the full entry map"""
  257. return get_distribution(dist).get_entry_map(group)
  258. def get_entry_info(dist, group, name):
  259. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  260. return get_distribution(dist).get_entry_info(group, name)
  261. class IMetadataProvider:
  262. def has_metadata(name):
  263. """Does the package's distribution contain the named metadata?"""
  264. def get_metadata(name):
  265. """The named metadata resource as a string"""
  266. def get_metadata_lines(name):
  267. """Yield named metadata resource as list of non-blank non-comment lines
  268. Leading and trailing whitespace is stripped from each line, and lines
  269. with ``#`` as the first non-blank character are omitted."""
  270. def metadata_isdir(name):
  271. """Is the named metadata a directory? (like ``os.path.isdir()``)"""
  272. def metadata_listdir(name):
  273. """List of metadata names in the directory (like ``os.listdir()``)"""
  274. def run_script(script_name, namespace):
  275. """Execute the named script in the supplied namespace dictionary"""
  276. class IResourceProvider(IMetadataProvider):
  277. """An object that provides access to package resources"""
  278. def get_resource_filename(manager, resource_name):
  279. """Return a true filesystem path for `resource_name`
  280. `manager` must be an ``IResourceManager``"""
  281. def get_resource_stream(manager, resource_name):
  282. """Return a readable file-like object for `resource_name`
  283. `manager` must be an ``IResourceManager``"""
  284. def get_resource_string(manager, resource_name):
  285. """Return a string containing the contents of `resource_name`
  286. `manager` must be an ``IResourceManager``"""
  287. def has_resource(resource_name):
  288. """Does the package contain the named resource?"""
  289. def resource_isdir(resource_name):
  290. """Is the named resource a directory? (like ``os.path.isdir()``)"""
  291. def resource_listdir(resource_name):
  292. """List of resource names in the directory (like ``os.listdir()``)"""
  293. class WorkingSet(object):
  294. """A collection of active distributions on sys.path (or a similar list)"""
  295. def __init__(self, entries=None):
  296. """Create working set from list of path entries (default=sys.path)"""
  297. self.entries = []
  298. self.entry_keys = {}
  299. self.by_key = {}
  300. self.callbacks = []
  301. if entries is None:
  302. entries = sys.path
  303. for entry in entries:
  304. self.add_entry(entry)
  305. def add_entry(self, entry):
  306. """Add a path item to ``.entries``, finding any distributions on it
  307. ``find_distributions(entry,True)`` is used to find distributions
  308. corresponding to the path entry, and they are added. `entry` is
  309. always appended to ``.entries``, even if it is already present.
  310. (This is because ``sys.path`` can contain the same value more than
  311. once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
  312. equal ``sys.path``.)
  313. """
  314. self.entry_keys.setdefault(entry, [])
  315. self.entries.append(entry)
  316. for dist in find_distributions(entry, True):
  317. self.add(dist, entry, False)
  318. def __contains__(self,dist):
  319. """True if `dist` is the active distribution for its project"""
  320. return self.by_key.get(dist.key) == dist
  321. def find(self, req):
  322. """Find a distribution matching requirement `req`
  323. If there is an active distribution for the requested project, this
  324. returns it as long as it meets the version requirement specified by
  325. `req`. But, if there is an active distribution for the project and it
  326. does *not* meet the `req` requirement, ``VersionConflict`` is raised.
  327. If there is no active distribution for the requested project, ``None``
  328. is returned.
  329. """
  330. dist = self.by_key.get(req.key)
  331. if dist is not None and dist not in req:
  332. raise VersionConflict(dist,req) # XXX add more info
  333. else:
  334. return dist
  335. def iter_entry_points(self, group, name=None):
  336. """Yield entry point objects from `group` matching `name`
  337. If `name` is None, yields all entry points in `group` from all
  338. distributions in the working set, otherwise only ones matching
  339. both `group` and `name` are yielded (in distribution order).
  340. """
  341. for dist in self:
  342. entries = dist.get_entry_map(group)
  343. if name is None:
  344. for ep in entries.values():
  345. yield ep
  346. elif name in entries:
  347. yield entries[name]
  348. def run_script(self, requires, script_name):
  349. """Locate distribution for `requires` and run `script_name` script"""
  350. ns = sys._getframe(1).f_globals
  351. name = ns['__name__']
  352. ns.clear()
  353. ns['__name__'] = name
  354. self.require(requires)[0].run_script(script_name, ns)
  355. def __iter__(self):
  356. """Yield distributions for non-duplicate projects in the working set
  357. The yield order is the order in which the items' path entries were
  358. added to the working set.
  359. """
  360. seen = {}
  361. for item in self.entries:
  362. if item not in self.entry_keys:
  363. # workaround a cache issue
  364. continue
  365. for key in self.entry_keys[item]:
  366. if key not in seen:
  367. seen[key]=1
  368. yield self.by_key[key]
  369. def add(self, dist, entry=None, insert=True):
  370. """Add `dist` to working set, associated with `entry`
  371. If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
  372. On exit from this routine, `entry` is added to the end of the working
  373. set's ``.entries`` (if it wasn't already present).
  374. `dist` is only added to the working set if it's for a project that
  375. doesn't already have a distribution in the set. If it's added, any
  376. callbacks registered with the ``subscribe()`` method will be called.
  377. """
  378. if insert:
  379. dist.insert_on(self.entries, entry)
  380. if entry is None:
  381. entry = dist.location
  382. keys = self.entry_keys.setdefault(entry,[])
  383. keys2 = self.entry_keys.setdefault(dist.location,[])
  384. if dist.key in self.by_key:
  385. return # ignore hidden distros
  386. self.by_key[dist.key] = dist
  387. if dist.key not in keys:
  388. keys.append(dist.key)
  389. if dist.key not in keys2:
  390. keys2.append(dist.key)
  391. self._added_new(dist)
  392. def resolve(self, requirements, env=None, installer=None, replacement=True):
  393. """List all distributions needed to (recursively) meet `requirements`
  394. `requirements` must be a sequence of ``Requirement`` objects. `env`,
  395. if supplied, should be an ``Environment`` instance. If
  396. not supplied, it defaults to all distributions available within any
  397. entry or distribution in the working set. `installer`, if supplied,
  398. will be invoked with each requirement that cannot be met by an
  399. already-installed distribution; it should return a ``Distribution`` or
  400. ``None``.
  401. """
  402. requirements = list(requirements)[::-1] # set up the stack
  403. processed = {} # set of processed requirements
  404. best = {} # key -> dist
  405. to_activate = []
  406. while requirements:
  407. req = requirements.pop(0) # process dependencies breadth-first
  408. if _override_setuptools(req) and replacement:
  409. req = Requirement.parse('distribute')
  410. if req in processed:
  411. # Ignore cyclic or redundant dependencies
  412. continue
  413. dist = best.get(req.key)
  414. if dist is None:
  415. # Find the best distribution and add it to the map
  416. dist = self.by_key.get(req.key)
  417. if dist is None:
  418. if env is None:
  419. env = Environment(self.entries)
  420. dist = best[req.key] = env.best_match(req, self, installer)
  421. if dist is None:
  422. #msg = ("The '%s' distribution was not found on this "
  423. # "system, and is required by this application.")
  424. #raise DistributionNotFound(msg % req)
  425. # unfortunately, zc.buildout uses a str(err)
  426. # to get the name of the distribution here..
  427. raise DistributionNotFound(req)
  428. to_activate.append(dist)
  429. if dist not in req:
  430. # Oops, the "best" so far conflicts with a dependency
  431. raise VersionConflict(dist,req) # XXX put more info here
  432. requirements.extend(dist.requires(req.extras)[::-1])
  433. processed[req] = True
  434. return to_activate # return list of distros to activate
  435. def find_plugins(self,
  436. plugin_env, full_env=None, installer=None, fallback=True
  437. ):
  438. """Find all activatable distributions in `plugin_env`
  439. Example usage::
  440. distributions, errors = working_set.find_plugins(
  441. Environment(plugin_dirlist)
  442. )
  443. map(working_set.add, distributions) # add plugins+libs to sys.path
  444. print 'Could not load', errors # display errors
  445. The `plugin_env` should be an ``Environment`` instance that contains
  446. only distributions that are in the project's "plugin directory" or
  447. directories. The `full_env`, if supplied, should be an ``Environment``
  448. contains all currently-available distributions. If `full_env` is not
  449. supplied, one is created automatically from the ``WorkingSet`` this
  450. method is called on, which will typically mean that every directory on
  451. ``sys.path`` will be scanned for distributions.
  452. `installer` is a standard installer callback as used by the
  453. ``resolve()`` method. The `fallback` flag indicates whether we should
  454. attempt to resolve older versions of a plugin if the newest version
  455. cannot be resolved.
  456. This method returns a 2-tuple: (`distributions`, `error_info`), where
  457. `distributions` is a list of the distributions found in `plugin_env`
  458. that were loadable, along with any other distributions that are needed
  459. to resolve their dependencies. `error_info` is a dictionary mapping
  460. unloadable plugin distributions to an exception instance describing the
  461. error that occurred. Usually this will be a ``DistributionNotFound`` or
  462. ``VersionConflict`` instance.
  463. """
  464. plugin_projects = list(plugin_env)
  465. plugin_projects.sort() # scan project names in alphabetic order
  466. error_info = {}
  467. distributions = {}
  468. if full_env is None:
  469. env = Environment(self.entries)
  470. env += plugin_env
  471. else:
  472. env = full_env + plugin_env
  473. shadow_set = self.__class__([])
  474. map(shadow_set.add, self) # put all our entries in shadow_set
  475. for project_name in plugin_projects:
  476. for dist in plugin_env[project_name]:
  477. req = [dist.as_requirement()]
  478. try:
  479. resolvees = shadow_set.resolve(req, env, installer)
  480. except ResolutionError,v:
  481. error_info[dist] = v # save error info
  482. if fallback:
  483. continue # try the next older version of project
  484. else:
  485. break # give up on this project, keep going
  486. else:
  487. map(shadow_set.add, resolvees)
  488. distributions.update(dict.fromkeys(resolvees))
  489. # success, no need to try any more versions of this project
  490. break
  491. distributions = list(distributions)
  492. distributions.sort()
  493. return distributions, error_info
  494. def require(self, *requirements):
  495. """Ensure that distributions matching `requirements` are activated
  496. `requirements` must be a string or a (possibly-nested) sequence
  497. thereof, specifying the distributions and versions required. The
  498. return value is a sequence of the distributions that needed to be
  499. activated to fulfill the requirements; all relevant distributions are
  500. included, even if they were already activated in this working set.
  501. """
  502. needed = self.resolve(parse_requirements(requirements))
  503. for dist in needed:
  504. self.add(dist)
  505. return needed
  506. def subscribe(self, callback):
  507. """Invoke `callback` for all distributions (including existing ones)"""
  508. if callback in self.callbacks:
  509. return
  510. self.callbacks.append(callback)
  511. for dist in self:
  512. callback(dist)
  513. def _added_new(self, dist):
  514. for callback in self.callbacks:
  515. callback(dist)
  516. def __getstate__(self):
  517. return (self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
  518. self.callbacks[:])
  519. def __setstate__(self, (entries, keys, by_key, callbacks)):
  520. self.entries = entries[:]
  521. self.entry_keys = keys.copy()
  522. self.by_key = by_key.copy()
  523. self.callbacks = callbacks[:]
  524. class Environment(object):
  525. """Searchable snapshot of distributions on a search path"""
  526. def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
  527. """Snapshot distributions available on a search path
  528. Any distributions found on `search_path` are added to the environment.
  529. `search_path` should be a sequence of ``sys.path`` items. If not
  530. supplied, ``sys.path`` is used.
  531. `platform` is an optional string specifying the name of the platform
  532. that platform-specific distributions must be compatible with. If
  533. unspecified, it defaults to the current platform. `python` is an
  534. optional string naming the desired version of Python (e.g. ``'2.4'``);
  535. it defaults to the current version.
  536. You may explicitly set `platform` (and/or `python`) to ``None`` if you
  537. wish to map *all* distributions, not just those compatible with the
  538. running platform or Python version.
  539. """
  540. self._distmap = {}
  541. self._cache = {}
  542. self.platform = platform
  543. self.python = python
  544. self.scan(search_path)
  545. def can_add(self, dist):
  546. """Is distribution `dist` acceptable for this environment?
  547. The distribution must match the platform and python version
  548. requirements specified when this environment was created, or False
  549. is returned.
  550. """
  551. return (self.python is None or dist.py_version is None
  552. or dist.py_version==self.python) \
  553. and compatible_platforms(dist.platform,self.platform)
  554. def remove(self, dist):
  555. """Remove `dist` from the environment"""
  556. self._distmap[dist.key].remove(dist)
  557. def scan(self, search_path=None):
  558. """Scan `search_path` for distributions usable in this environment
  559. Any distributions found are added to the environment.
  560. `search_path` should be a sequence of ``sys.path`` items. If not
  561. supplied, ``sys.path`` is used. Only distributions conforming to
  562. the platform/python version defined at initialization are added.
  563. """
  564. if search_path is None:
  565. search_path = sys.path
  566. for item in search_path:
  567. for dist in find_distributions(item):
  568. self.add(dist)
  569. def __getitem__(self,project_name):
  570. """Return a newest-to-oldest list of distributions for `project_name`
  571. """
  572. try:
  573. return self._cache[project_name]
  574. except KeyError:
  575. project_name = project_name.lower()
  576. if project_name not in self._distmap:
  577. return []
  578. if project_name not in self._cache:
  579. dists = self._cache[project_name] = self._distmap[project_name]
  580. _sort_dists(dists)
  581. return self._cache[project_name]
  582. def add(self,dist):
  583. """Add `dist` if we ``can_add()`` it and it isn't already added"""
  584. if self.can_add(dist) and dist.has_version():
  585. dists = self._distmap.setdefault(dist.key,[])
  586. if dist not in dists:
  587. dists.append(dist)
  588. if dist.key in self._cache:
  589. _sort_dists(self._cache[dist.key])
  590. def best_match(self, req, working_set, installer=None):
  591. """Find distribution best matching `req` and usable on `working_set`
  592. This calls the ``find(req)`` method of the `working_set` to see if a
  593. suitable distribution is already active. (This may raise
  594. ``VersionConflict`` if an unsuitable version of the project is already
  595. active in the specified `working_set`.) If a suitable distribution
  596. isn't active, this method returns the newest distribution in the
  597. environment that meets the ``Requirement`` in `req`. If no suitable
  598. distribution is found, and `installer` is supplied, then the result of
  599. calling the environment's ``obtain(req, installer)`` method will be
  600. returned.
  601. """
  602. dist = working_set.find(req)
  603. if dist is not None:
  604. return dist
  605. for dist in self[req.key]:
  606. if dist in req:
  607. return dist
  608. return self.obtain(req, installer) # try and download/install
  609. def obtain(self, requirement, installer=None):
  610. """Obtain a distribution matching `requirement` (e.g. via download)
  611. Obtain a distro that matches requirement (e.g. via download). In the
  612. base ``Environment`` class, this routine just returns
  613. ``installer(requirement)``, unless `installer` is None, in which case
  614. None is returned instead. This method is a hook that allows subclasses
  615. to attempt other ways of obtaining a distribution before falling back
  616. to the `installer` argument."""
  617. if installer is not None:
  618. return installer(requirement)
  619. def __iter__(self):
  620. """Yield the unique project names of the available distributions"""
  621. for key in self._distmap.keys():
  622. if self[key]: yield key
  623. def __iadd__(self, other):
  624. """In-place addition of a distribution or environment"""
  625. if isinstance(other,Distribution):
  626. self.add(other)
  627. elif isinstance(other,Environment):
  628. for project in other:
  629. for dist in other[project]:
  630. self.add(dist)
  631. else:
  632. raise TypeError("Can't add %r to environment" % (other,))
  633. return self
  634. def __add__(self, other):
  635. """Add an environment or distribution to an environment"""
  636. new = self.__class__([], platform=None, python=None)
  637. for env in self, other:
  638. new += env
  639. return new
  640. AvailableDistributions = Environment # XXX backward compatibility
  641. class ExtractionError(RuntimeError):
  642. """An error occurred extracting a resource
  643. The following attributes are available from instances of this exception:
  644. manager
  645. The resource manager that raised this exception
  646. cache_path
  647. The base directory for resource extraction
  648. original_error
  649. The exception instance that caused extraction to fail
  650. """
  651. class ResourceManager:
  652. """Manage resource extraction and packages"""
  653. extraction_path = None
  654. def __init__(self):
  655. self.cached_files = {}
  656. def resource_exists(self, package_or_requirement, resource_name):
  657. """Does the named resource exist?"""
  658. return get_provider(package_or_requirement).has_resource(resource_name)
  659. def resource_isdir(self, package_or_requirement, resource_name):
  660. """Is the named resource an existing directory?"""
  661. return get_provider(package_or_requirement).resource_isdir(
  662. resource_name
  663. )
  664. def resource_filename(self, package_or_requirement, resource_name):
  665. """Return a true filesystem path for specified resource"""
  666. return get_provider(package_or_requirement).get_resource_filename(
  667. self, resource_name
  668. )
  669. def resource_stream(self, package_or_requirement, resource_name):
  670. """Return a readable file-like object for specified resource"""
  671. return get_provider(package_or_requirement).get_resource_stream(
  672. self, resource_name
  673. )
  674. def resource_string(self, package_or_requirement, resource_name):
  675. """Return specified resource as a string"""
  676. return get_provider(package_or_requirement).get_resource_string(
  677. self, resource_name
  678. )
  679. def resource_listdir(self, package_or_requirement, resource_name):
  680. """List the contents of the named resource directory"""
  681. return get_provider(package_or_requirement).resource_listdir(
  682. resource_name
  683. )
  684. def extraction_error(self):
  685. """Give an error message for problems extracting file(s)"""
  686. old_exc = sys.exc_info()[1]
  687. cache_path = self.extraction_path or get_default_cache()
  688. err = ExtractionError("""Can't extract file(s) to egg cache
  689. The following error occurred while trying to extract file(s) to the Python egg
  690. cache:
  691. %s
  692. The Python egg cache directory is currently set to:
  693. %s
  694. Perhaps your account does not have write access to this directory? You can
  695. change the cache directory by setting the PYTHON_EGG_CACHE environment
  696. variable to point to an accessible directory.
  697. """ % (old_exc, cache_path)
  698. )
  699. err.manager = self
  700. err.cache_path = cache_path
  701. err.original_error = old_exc
  702. raise err
  703. def get_cache_path(self, archive_name, names=()):
  704. """Return absolute location in cache for `archive_name` and `names`
  705. The parent directory of the resulting path will be created if it does
  706. not already exist. `archive_name` should be the base filename of the
  707. enclosing egg (which may not be the name of the enclosing zipfile!),
  708. including its ".egg" extension. `names`, if provided, should be a
  709. sequence of path name parts "under" the egg's extraction location.
  710. This method should only be called by resource providers that need to
  711. obtain an extraction location, and only for names they intend to
  712. extract, as it tracks the generated names for possible cleanup later.
  713. """
  714. extract_path = self.extraction_path or get_default_cache()
  715. target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
  716. try:
  717. _bypass_ensure_directory(target_path)
  718. except:
  719. self.extraction_error()
  720. self.cached_files[target_path] = 1
  721. return target_path
  722. def postprocess(self, tempname, filename):
  723. """Perform any platform-specific postprocessing of `tempname`
  724. This is where Mac header rewrites should be done; other platforms don't
  725. have anything special they should do.
  726. Resource providers should call this method ONLY after successfully
  727. extracting a compressed resource. They must NOT call it on resources
  728. that are already in the filesystem.
  729. `tempname` is the current (temporary) name of the file, and `filename`
  730. is the name it will be renamed to by the caller after this routine
  731. returns.
  732. """
  733. if os.name == 'posix':
  734. # Make the resource executable
  735. mode = ((os.stat(tempname).st_mode) | 0555) & 07777
  736. os.chmod(tempname, mode)
  737. def set_extraction_path(self, path):
  738. """Set the base path where resources will be extracted to, if needed.
  739. If you do not call this routine before any extractions take place, the
  740. path defaults to the return value of ``get_default_cache()``. (Which
  741. is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  742. platform-specific fallbacks. See that routine's documentation for more
  743. details.)
  744. Resources are extracted to subdirectories of this path based upon
  745. information given by the ``IResourceProvider``. You may set this to a
  746. temporary directory, but then you must call ``cleanup_resources()`` to
  747. delete the extracted files when done. There is no guarantee that
  748. ``cleanup_resources()`` will be able to remove all extracted files.
  749. (Note: you may not change the extraction path for a given resource
  750. manager once resources have been extracted, unless you first call
  751. ``cleanup_resources()``.)
  752. """
  753. if self.cached_files:
  754. raise ValueError(
  755. "Can't change extraction path, files already extracted"
  756. )
  757. self.extraction_path = path
  758. def cleanup_resources(self, force=False):
  759. """
  760. Delete all extracted resource files and directories, returning a list
  761. of the file and directory names that could not be successfully removed.
  762. This function does not have any concurrency protection, so it should
  763. generally only be called when the extraction path is a temporary
  764. directory exclusive to a single process. This method is not
  765. automatically called; you must call it explicitly or register it as an
  766. ``atexit`` function if you wish to ensure cleanup of a temporary
  767. directory used for extractions.
  768. """
  769. # XXX
  770. def get_default_cache():
  771. """Determine the default cache location
  772. This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
  773. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
  774. "Application Data" directory. On all other systems, it's "~/.python-eggs".
  775. """
  776. try:
  777. return os.environ['PYTHON_EGG_CACHE']
  778. except KeyError:
  779. pass
  780. if os.name!='nt':
  781. return os.path.expanduser('~/.python-eggs')
  782. app_data = 'Application Data' # XXX this may be locale-specific!
  783. app_homes = [
  784. (('APPDATA',), None), # best option, should be locale-safe
  785. (('USERPROFILE',), app_data),
  786. (('HOMEDRIVE','HOMEPATH'), app_data),
  787. (('HOMEPATH',), app_data),
  788. (('HOME',), None),
  789. (('WINDIR',), app_data), # 95/98/ME
  790. ]
  791. for keys, subdir in app_homes:
  792. dirname = ''
  793. for key in keys:
  794. if key in os.environ:
  795. dirname = os.path.join(dirname, os.environ[key])
  796. else:
  797. break
  798. else:
  799. if subdir:
  800. dirname = os.path.join(dirname,subdir)
  801. return os.path.join(dirname, 'Python-Eggs')
  802. else:
  803. raise RuntimeError(
  804. "Please set the PYTHON_EGG_CACHE enviroment variable"
  805. )
  806. def safe_name(name):
  807. """Convert an arbitrary string to a standard distribution name
  808. Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  809. """
  810. return re.sub('[^A-Za-z0-9.]+', '-', name)
  811. def safe_version(version):
  812. """Convert an arbitrary string to a standard version string
  813. Spaces become dots, and all other non-alphanumeric characters become
  814. dashes, with runs of multiple dashes condensed to a single dash.
  815. """
  816. version = version.replace(' ','.')
  817. return re.sub('[^A-Za-z0-9.]+', '-', version)
  818. def safe_extra(extra):
  819. """Convert an arbitrary string to a standard 'extra' name
  820. Any runs of non-alphanumeric characters are replaced with a single '_',
  821. and the result is always lowercased.
  822. """
  823. return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  824. def to_filename(name):
  825. """Convert a project or version name to its filename-escaped form
  826. Any '-' characters are currently replaced with '_'.
  827. """
  828. return name.replace('-','_')
  829. class NullProvider:
  830. """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
  831. egg_name = None
  832. egg_info = None
  833. loader = None
  834. def __init__(self, module):
  835. self.loader = getattr(module, '__loader__', None)
  836. self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  837. def get_resource_filename(self, manager, resource_name):
  838. return self._fn(self.module_path, resource_name)
  839. def get_resource_stream(self, manager, resource_name):
  840. return StringIO(self.get_resource_string(manager, resource_name))
  841. def get_resource_string(self, manager, resource_name):
  842. return self._get(self._fn(self.module_path, resource_name))
  843. def has_resource(self, resource_name):
  844. return self._has(self._fn(self.module_path, resource_name))
  845. def has_metadata(self, name):
  846. return self.egg_info and self._has(self._fn(self.egg_info,name))
  847. if sys.version_info <= (3,):
  848. def get_metadata(self, name):
  849. if not self.egg_info:
  850. return ""
  851. return self._get(self._fn(self.egg_info,name))
  852. else:
  853. def get_metadata(self, name):
  854. if not self.egg_info:
  855. return ""
  856. return self._get(self._fn(self.egg_info,name)).decode("utf-8")
  857. def get_metadata_lines(self, name):
  858. return yield_lines(self.get_metadata(name))
  859. def resource_isdir(self,resource_name):
  860. return self._isdir(self._fn(self.module_path, resource_name))
  861. def metadata_isdir(self,name):
  862. return self.egg_info and self._isdir(self._fn(self.egg_info,name))
  863. def resource_listdir(self,resource_name):
  864. return self._listdir(self._fn(self.module_path,resource_name))
  865. def metadata_listdir(self,name):
  866. if self.egg_info:
  867. return self._listdir(self._fn(self.egg_info,name))
  868. return []
  869. def run_script(self,script_name,namespace):
  870. script = 'scripts/'+script_name
  871. if not self.has_metadata(script):
  872. raise ResolutionError("No script named %r" % script_name)
  873. script_text = self.get_metadata(script).replace('\r\n','\n')
  874. script_text = script_text.replace('\r','\n')
  875. script_filename = self._fn(self.egg_info,script)
  876. namespace['__file__'] = script_filename
  877. if os.path.exists(script_filename):
  878. execfile(script_filename, namespace, namespace)
  879. else:
  880. from linecache import cache
  881. cache[script_filename] = (
  882. len(script_text), 0, script_text.split('\n'), script_filename
  883. )
  884. script_code = compile(script_text,script_filename,'exec')
  885. exec script_code in namespace, namespace
  886. def _has(self, path):
  887. raise NotImplementedError(
  888. "Can't perform this operation for unregistered loader type"
  889. )
  890. def _isdir(self, path):
  891. raise NotImplementedError(
  892. "Can't perform this operation for unregistered loader type"
  893. )
  894. def _listdir(self, path):
  895. raise NotImplementedError(
  896. "Can't perform this operation for unregistered loader type"
  897. )
  898. def _fn(self, base, resource_name):
  899. if resource_name:
  900. return os.path.join(base, *resource_name.split('/'))
  901. return base
  902. def _get(self, path):
  903. if hasattr(self.loader, 'get_data'):
  904. return self.loader.get_data(path)
  905. raise NotImplementedError(
  906. "Can't perform this operation for loaders without 'get_data()'"
  907. )
  908. register_loader_type(object, NullProvider)
  909. class EggProvider(NullProvider):
  910. """Provider based on a virtual filesystem"""
  911. def __init__(self,module):
  912. NullProvider.__init__(self,module)
  913. self._setup_prefix()
  914. def _setup_prefix(self):
  915. # we assume here that our metadata may be nested inside a "basket"
  916. # of multiple eggs; that's why we use module_path instead of .archive
  917. path = self.module_path
  918. old = None
  919. while path!=old:
  920. if path.lower().endswith('.egg'):
  921. self.egg_name = os.path.basename(path)
  922. self.egg_info = os.path.join(path, 'EGG-INFO')
  923. self.egg_root = path
  924. break
  925. old = path
  926. path, base = os.path.split(path)
  927. class DefaultProvider(EggProvider):
  928. """Provides access to package resources in the filesystem"""
  929. def _has(self, path):
  930. return os.path.exists(path)
  931. def _isdir(self,path):
  932. return os.path.isdir(path)
  933. def _listdir(self,path):
  934. return os.listdir(path)
  935. def get_resource_stream(self, manager, resource_name):
  936. return open(self._fn(self.module_path, resource_name), 'rb')
  937. def _get(self, path):
  938. stream = open(path, 'rb')
  939. try:
  940. return stream.read()
  941. finally:
  942. stream.close()
  943. register_loader_type(type(None), DefaultProvider)
  944. try:
  945. # CPython >=3.3
  946. import _frozen_importlib
  947. except ImportError:
  948. pass
  949. else:
  950. register_loader_type(_frozen_importlib.SourceFileLoader, DefaultProvider)
  951. class EmptyProvider(NullProvider):
  952. """Provider that returns nothing for all requests"""
  953. _isdir = _has = lambda self,path: False
  954. _get = lambda self,path: ''
  955. _listdir = lambda self,path: []
  956. module_path = None
  957. def __init__(self):
  958. pass
  959. empty_provider = EmptyProvider()
  960. class ZipProvider(EggProvider):
  961. """Resource support for zips and eggs"""
  962. eagers = None
  963. def __init__(self, module):
  964. EggProvider.__init__(self,module)
  965. self.zipinfo = zipimport._zip_directory_cache[self.loader.archive]
  966. self.zip_pre = self.loader.archive+os.sep
  967. def _zipinfo_name(self, fspath):
  968. # Convert a virtual filename (full path to file) into a zipfile subpath
  969. # usable with the zipimport directory cache for our target archive
  970. if fspath.startswith(self.zip_pre):
  971. return fspath[len(self.zip_pre):]
  972. raise AssertionError(
  973. "%s is not a subpath of %s" % (fspath,self.zip_pre)
  974. )
  975. def _parts(self,zip_path):
  976. # Convert a zipfile subpath into an egg-relative path part list
  977. fspath = self.zip_pre+zip_path # pseudo-fs path
  978. if fspath.startswith(self.egg_root+os.sep):
  979. return fspath[len(self.egg_root)+1:].split(os.sep)
  980. raise AssertionError(
  981. "%s is not a subpath of %s" % (fspath,self.egg_root)
  982. )
  983. def get_resource_filename(self, manager, resource_name):
  984. if not self.egg_name:
  985. raise NotImplementedError(
  986. "resource_filename() only supported for .egg, not .zip"
  987. )
  988. # no need to lock for extraction, since we use temp names
  989. zip_path = self._resource_to_zip(resource_name)
  990. eagers = self._get_eager_resources()
  991. if '/'.join(self._parts(zip_path)) in eagers:
  992. for name in eagers:
  993. self._extract_resource(manager, self._eager_to_zip(name))
  994. return self._extract_resource(manager, zip_path)
  995. def _extract_resource(self, manager, zip_path):
  996. if zip_path in self._index():
  997. for name in self._index()[zip_path]:
  998. last = self._extract_resource(
  999. manager, os.path.join(zip_path, name)
  1000. )
  1001. return os.path.dirname(last) # return the extracted directory name
  1002. zip_stat = self.zipinfo[zip_path]
  1003. t,d,size = zip_stat[5], zip_stat[6], zip_stat[3]
  1004. date_time = (
  1005. (d>>9)+1980, (d>>5)&0xF, d&0x1F, # ymd
  1006. (t&0xFFFF)>>11, (t>>5)&0x3F, (t&0x1F) * 2, 0, 0, -1 # hms, etc.
  1007. )
  1008. timestamp = time.mktime(date_time)
  1009. try:
  1010. if not WRITE_SUPPORT:
  1011. raise IOError('"os.rename" and "os.unlink" are not supported '
  1012. 'on this platform')
  1013. real_path = manager.get_cache_path(
  1014. self.egg_name, self._parts(zip_path)
  1015. )
  1016. if os.path.isfile(real_path):
  1017. stat = os.stat(real_path)
  1018. if stat.st_size==size and stat.st_mtime==timestamp:
  1019. # size and stamp match, don't bother extracting
  1020. return real_path
  1021. outf, tmpnam = _mkstemp(".$extract", dir=os.path.dirname(real_path))
  1022. os.write(outf, self.loader.get_data(zip_path))
  1023. os.close(outf)
  1024. utime(tmpnam, (timestamp,timestamp))
  1025. manager.postprocess(tmpnam, real_path)
  1026. try:
  1027. rename(tmpnam, real_path)
  1028. except os.error:
  1029. if os.path.isfile(real_path):
  1030. stat = os.stat(real_path)
  1031. if stat.st_size==size and stat.st_mtime==timestamp:
  1032. # size and stamp match, somebody did it just ahead of
  1033. # us, so we're done
  1034. return real_path
  1035. elif os.name=='nt': # Windows, del old file and retry
  1036. unlink(real_path)
  1037. rename(tmpnam, real_path)
  1038. return real_path
  1039. raise
  1040. except os.error:
  1041. manager.extraction_error() # report a user-friendly error
  1042. return real_path
  1043. def _get_eager_resources(self):
  1044. if self.eagers is None:
  1045. eagers = []
  1046. for name in ('native_libs.txt', 'eager_resources.txt'):
  1047. if self.has_metadata(name):
  1048. eagers.extend(self.get_metadata_lines(name))
  1049. self.eagers = eagers
  1050. return self.eagers
  1051. def _index(self):
  1052. try:
  1053. return self._dirindex
  1054. except AttributeError:
  1055. ind = {}
  1056. for path in self.zipinfo:
  1057. parts = path.split(os.sep)
  1058. while parts:
  1059. parent = os.sep.join(parts[:-1])
  1060. if parent in ind:
  1061. ind[parent].append(parts[-1])
  1062. break
  1063. else:
  1064. ind[parent] = [parts.pop()]
  1065. self._dirindex = ind
  1066. return ind
  1067. def _has(self, fspath):
  1068. zip_path = self._zipinfo_name(fspath)
  1069. return zip_path in self.zipinfo or zip_path in self._index()
  1070. def _isdir(self,fspath):
  1071. return self._zipinfo_name(fspath) in self._index()
  1072. def _listdir(self,fs

Large files files are truncated, but you can click here to view the full file