PageRenderTime 67ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/hd-venv/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py

https://github.com/Riegerb/GSWD_Tutorial
Python | 2851 lines | 2703 code | 86 blank | 62 comment | 60 complexity | c5b2d7501bec27ba4d6bee2f9079e255 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, replace=False):
  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, unless `replace=True`.
  376. If it's added, any callbacks registered with the ``subscribe()`` method
  377. will be called.
  378. """
  379. if insert:
  380. dist.insert_on(self.entries, entry)
  381. if entry is None:
  382. entry = dist.location
  383. keys = self.entry_keys.setdefault(entry,[])
  384. keys2 = self.entry_keys.setdefault(dist.location,[])
  385. if not replace and dist.key in self.by_key:
  386. return # ignore hidden distros
  387. self.by_key[dist.key] = dist
  388. if dist.key not in keys:
  389. keys.append(dist.key)
  390. if dist.key not in keys2:
  391. keys2.append(dist.key)
  392. self._added_new(dist)
  393. def resolve(self, requirements, env=None, installer=None,
  394. replacement=True, replace_conflicting=False):
  395. """List all distributions needed to (recursively) meet `requirements`
  396. `requirements` must be a sequence of ``Requirement`` objects. `env`,
  397. if supplied, should be an ``Environment`` instance. If
  398. not supplied, it defaults to all distributions available within any
  399. entry or distribution in the working set. `installer`, if supplied,
  400. will be invoked with each requirement that cannot be met by an
  401. already-installed distribution; it should return a ``Distribution`` or
  402. ``None``.
  403. Unless `replace_conflicting=True`, raises a VersionConflict exception if
  404. any requirements are found on the path that have the correct name but
  405. the wrong version. Otherwise, if an `installer` is supplied it will be
  406. invoked to obtain the correct version of the requirement and activate
  407. it.
  408. """
  409. requirements = list(requirements)[::-1] # set up the stack
  410. processed = {} # set of processed requirements
  411. best = {} # key -> dist
  412. to_activate = []
  413. while requirements:
  414. req = requirements.pop(0) # process dependencies breadth-first
  415. if _override_setuptools(req) and replacement:
  416. req = Requirement.parse('distribute')
  417. if req in processed:
  418. # Ignore cyclic or redundant dependencies
  419. continue
  420. dist = best.get(req.key)
  421. if dist is None:
  422. # Find the best distribution and add it to the map
  423. dist = self.by_key.get(req.key)
  424. if dist is None or (dist not in req and replace_conflicting):
  425. ws = self
  426. if env is None:
  427. if dist is None:
  428. env = Environment(self.entries)
  429. else:
  430. # Use an empty environment and workingset to avoid
  431. # any further conflicts with the conflicting
  432. # distribution
  433. env = Environment([])
  434. ws = WorkingSet([])
  435. dist = best[req.key] = env.best_match(req, ws, installer)
  436. if dist is None:
  437. #msg = ("The '%s' distribution was not found on this "
  438. # "system, and is required by this application.")
  439. #raise DistributionNotFound(msg % req)
  440. # unfortunately, zc.buildout uses a str(err)
  441. # to get the name of the distribution here..
  442. raise DistributionNotFound(req)
  443. to_activate.append(dist)
  444. if dist not in req:
  445. # Oops, the "best" so far conflicts with a dependency
  446. raise VersionConflict(dist,req) # XXX put more info here
  447. requirements.extend(dist.requires(req.extras)[::-1])
  448. processed[req] = True
  449. return to_activate # return list of distros to activate
  450. def find_plugins(self,
  451. plugin_env, full_env=None, installer=None, fallback=True
  452. ):
  453. """Find all activatable distributions in `plugin_env`
  454. Example usage::
  455. distributions, errors = working_set.find_plugins(
  456. Environment(plugin_dirlist)
  457. )
  458. map(working_set.add, distributions) # add plugins+libs to sys.path
  459. print 'Could not load', errors # display errors
  460. The `plugin_env` should be an ``Environment`` instance that contains
  461. only distributions that are in the project's "plugin directory" or
  462. directories. The `full_env`, if supplied, should be an ``Environment``
  463. contains all currently-available distributions. If `full_env` is not
  464. supplied, one is created automatically from the ``WorkingSet`` this
  465. method is called on, which will typically mean that every directory on
  466. ``sys.path`` will be scanned for distributions.
  467. `installer` is a standard installer callback as used by the
  468. ``resolve()`` method. The `fallback` flag indicates whether we should
  469. attempt to resolve older versions of a plugin if the newest version
  470. cannot be resolved.
  471. This method returns a 2-tuple: (`distributions`, `error_info`), where
  472. `distributions` is a list of the distributions found in `plugin_env`
  473. that were loadable, along with any other distributions that are needed
  474. to resolve their dependencies. `error_info` is a dictionary mapping
  475. unloadable plugin distributions to an exception instance describing the
  476. error that occurred. Usually this will be a ``DistributionNotFound`` or
  477. ``VersionConflict`` instance.
  478. """
  479. plugin_projects = list(plugin_env)
  480. plugin_projects.sort() # scan project names in alphabetic order
  481. error_info = {}
  482. distributions = {}
  483. if full_env is None:
  484. env = Environment(self.entries)
  485. env += plugin_env
  486. else:
  487. env = full_env + plugin_env
  488. shadow_set = self.__class__([])
  489. map(shadow_set.add, self) # put all our entries in shadow_set
  490. for project_name in plugin_projects:
  491. for dist in plugin_env[project_name]:
  492. req = [dist.as_requirement()]
  493. try:
  494. resolvees = shadow_set.resolve(req, env, installer)
  495. except ResolutionError,v:
  496. error_info[dist] = v # save error info
  497. if fallback:
  498. continue # try the next older version of project
  499. else:
  500. break # give up on this project, keep going
  501. else:
  502. map(shadow_set.add, resolvees)
  503. distributions.update(dict.fromkeys(resolvees))
  504. # success, no need to try any more versions of this project
  505. break
  506. distributions = list(distributions)
  507. distributions.sort()
  508. return distributions, error_info
  509. def require(self, *requirements):
  510. """Ensure that distributions matching `requirements` are activated
  511. `requirements` must be a string or a (possibly-nested) sequence
  512. thereof, specifying the distributions and versions required. The
  513. return value is a sequence of the distributions that needed to be
  514. activated to fulfill the requirements; all relevant distributions are
  515. included, even if they were already activated in this working set.
  516. """
  517. needed = self.resolve(parse_requirements(requirements))
  518. for dist in needed:
  519. self.add(dist)
  520. return needed
  521. def subscribe(self, callback):
  522. """Invoke `callback` for all distributions (including existing ones)"""
  523. if callback in self.callbacks:
  524. return
  525. self.callbacks.append(callback)
  526. for dist in self:
  527. callback(dist)
  528. def _added_new(self, dist):
  529. for callback in self.callbacks:
  530. callback(dist)
  531. def __getstate__(self):
  532. return (self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
  533. self.callbacks[:])
  534. def __setstate__(self, (entries, keys, by_key, callbacks)):
  535. self.entries = entries[:]
  536. self.entry_keys = keys.copy()
  537. self.by_key = by_key.copy()
  538. self.callbacks = callbacks[:]
  539. class Environment(object):
  540. """Searchable snapshot of distributions on a search path"""
  541. def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
  542. """Snapshot distributions available on a search path
  543. Any distributions found on `search_path` are added to the environment.
  544. `search_path` should be a sequence of ``sys.path`` items. If not
  545. supplied, ``sys.path`` is used.
  546. `platform` is an optional string specifying the name of the platform
  547. that platform-specific distributions must be compatible with. If
  548. unspecified, it defaults to the current platform. `python` is an
  549. optional string naming the desired version of Python (e.g. ``'2.4'``);
  550. it defaults to the current version.
  551. You may explicitly set `platform` (and/or `python`) to ``None`` if you
  552. wish to map *all* distributions, not just those compatible with the
  553. running platform or Python version.
  554. """
  555. self._distmap = {}
  556. self._cache = {}
  557. self.platform = platform
  558. self.python = python
  559. self.scan(search_path)
  560. def can_add(self, dist):
  561. """Is distribution `dist` acceptable for this environment?
  562. The distribution must match the platform and python version
  563. requirements specified when this environment was created, or False
  564. is returned.
  565. """
  566. return (self.python is None or dist.py_version is None
  567. or dist.py_version==self.python) \
  568. and compatible_platforms(dist.platform,self.platform)
  569. def remove(self, dist):
  570. """Remove `dist` from the environment"""
  571. self._distmap[dist.key].remove(dist)
  572. def scan(self, search_path=None):
  573. """Scan `search_path` for distributions usable in this environment
  574. Any distributions found are added to the environment.
  575. `search_path` should be a sequence of ``sys.path`` items. If not
  576. supplied, ``sys.path`` is used. Only distributions conforming to
  577. the platform/python version defined at initialization are added.
  578. """
  579. if search_path is None:
  580. search_path = sys.path
  581. for item in search_path:
  582. for dist in find_distributions(item):
  583. self.add(dist)
  584. def __getitem__(self,project_name):
  585. """Return a newest-to-oldest list of distributions for `project_name`
  586. """
  587. try:
  588. return self._cache[project_name]
  589. except KeyError:
  590. project_name = project_name.lower()
  591. if project_name not in self._distmap:
  592. return []
  593. if project_name not in self._cache:
  594. dists = self._cache[project_name] = self._distmap[project_name]
  595. _sort_dists(dists)
  596. return self._cache[project_name]
  597. def add(self,dist):
  598. """Add `dist` if we ``can_add()`` it and it isn't already added"""
  599. if self.can_add(dist) and dist.has_version():
  600. dists = self._distmap.setdefault(dist.key,[])
  601. if dist not in dists:
  602. dists.append(dist)
  603. if dist.key in self._cache:
  604. _sort_dists(self._cache[dist.key])
  605. def best_match(self, req, working_set, installer=None):
  606. """Find distribution best matching `req` and usable on `working_set`
  607. This calls the ``find(req)`` method of the `working_set` to see if a
  608. suitable distribution is already active. (This may raise
  609. ``VersionConflict`` if an unsuitable version of the project is already
  610. active in the specified `working_set`.) If a suitable distribution
  611. isn't active, this method returns the newest distribution in the
  612. environment that meets the ``Requirement`` in `req`. If no suitable
  613. distribution is found, and `installer` is supplied, then the result of
  614. calling the environment's ``obtain(req, installer)`` method will be
  615. returned.
  616. """
  617. dist = working_set.find(req)
  618. if dist is not None:
  619. return dist
  620. for dist in self[req.key]:
  621. if dist in req:
  622. return dist
  623. return self.obtain(req, installer) # try and download/install
  624. def obtain(self, requirement, installer=None):
  625. """Obtain a distribution matching `requirement` (e.g. via download)
  626. Obtain a distro that matches requirement (e.g. via download). In the
  627. base ``Environment`` class, this routine just returns
  628. ``installer(requirement)``, unless `installer` is None, in which case
  629. None is returned instead. This method is a hook that allows subclasses
  630. to attempt other ways of obtaining a distribution before falling back
  631. to the `installer` argument."""
  632. if installer is not None:
  633. return installer(requirement)
  634. def __iter__(self):
  635. """Yield the unique project names of the available distributions"""
  636. for key in self._distmap.keys():
  637. if self[key]: yield key
  638. def __iadd__(self, other):
  639. """In-place addition of a distribution or environment"""
  640. if isinstance(other,Distribution):
  641. self.add(other)
  642. elif isinstance(other,Environment):
  643. for project in other:
  644. for dist in other[project]:
  645. self.add(dist)
  646. else:
  647. raise TypeError("Can't add %r to environment" % (other,))
  648. return self
  649. def __add__(self, other):
  650. """Add an environment or distribution to an environment"""
  651. new = self.__class__([], platform=None, python=None)
  652. for env in self, other:
  653. new += env
  654. return new
  655. AvailableDistributions = Environment # XXX backward compatibility
  656. class ExtractionError(RuntimeError):
  657. """An error occurred extracting a resource
  658. The following attributes are available from instances of this exception:
  659. manager
  660. The resource manager that raised this exception
  661. cache_path
  662. The base directory for resource extraction
  663. original_error
  664. The exception instance that caused extraction to fail
  665. """
  666. class ResourceManager:
  667. """Manage resource extraction and packages"""
  668. extraction_path = None
  669. def __init__(self):
  670. self.cached_files = {}
  671. def resource_exists(self, package_or_requirement, resource_name):
  672. """Does the named resource exist?"""
  673. return get_provider(package_or_requirement).has_resource(resource_name)
  674. def resource_isdir(self, package_or_requirement, resource_name):
  675. """Is the named resource an existing directory?"""
  676. return get_provider(package_or_requirement).resource_isdir(
  677. resource_name
  678. )
  679. def resource_filename(self, package_or_requirement, resource_name):
  680. """Return a true filesystem path for specified resource"""
  681. return get_provider(package_or_requirement).get_resource_filename(
  682. self, resource_name
  683. )
  684. def resource_stream(self, package_or_requirement, resource_name):
  685. """Return a readable file-like object for specified resource"""
  686. return get_provider(package_or_requirement).get_resource_stream(
  687. self, resource_name
  688. )
  689. def resource_string(self, package_or_requirement, resource_name):
  690. """Return specified resource as a string"""
  691. return get_provider(package_or_requirement).get_resource_string(
  692. self, resource_name
  693. )
  694. def resource_listdir(self, package_or_requirement, resource_name):
  695. """List the contents of the named resource directory"""
  696. return get_provider(package_or_requirement).resource_listdir(
  697. resource_name
  698. )
  699. def extraction_error(self):
  700. """Give an error message for problems extracting file(s)"""
  701. old_exc = sys.exc_info()[1]
  702. cache_path = self.extraction_path or get_default_cache()
  703. err = ExtractionError("""Can't extract file(s) to egg cache
  704. The following error occurred while trying to extract file(s) to the Python egg
  705. cache:
  706. %s
  707. The Python egg cache directory is currently set to:
  708. %s
  709. Perhaps your account does not have write access to this directory? You can
  710. change the cache directory by setting the PYTHON_EGG_CACHE environment
  711. variable to point to an accessible directory.
  712. """ % (old_exc, cache_path)
  713. )
  714. err.manager = self
  715. err.cache_path = cache_path
  716. err.original_error = old_exc
  717. raise err
  718. def get_cache_path(self, archive_name, names=()):
  719. """Return absolute location in cache for `archive_name` and `names`
  720. The parent directory of the resulting path will be created if it does
  721. not already exist. `archive_name` should be the base filename of the
  722. enclosing egg (which may not be the name of the enclosing zipfile!),
  723. including its ".egg" extension. `names`, if provided, should be a
  724. sequence of path name parts "under" the egg's extraction location.
  725. This method should only be called by resource providers that need to
  726. obtain an extraction location, and only for names they intend to
  727. extract, as it tracks the generated names for possible cleanup later.
  728. """
  729. extract_path = self.extraction_path or get_default_cache()
  730. target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
  731. try:
  732. _bypass_ensure_directory(target_path)
  733. except:
  734. self.extraction_error()
  735. self.cached_files[target_path] = 1
  736. return target_path
  737. def postprocess(self, tempname, filename):
  738. """Perform any platform-specific postprocessing of `tempname`
  739. This is where Mac header rewrites should be done; other platforms don't
  740. have anything special they should do.
  741. Resource providers should call this method ONLY after successfully
  742. extracting a compressed resource. They must NOT call it on resources
  743. that are already in the filesystem.
  744. `tempname` is the current (temporary) name of the file, and `filename`
  745. is the name it will be renamed to by the caller after this routine
  746. returns.
  747. """
  748. if os.name == 'posix':
  749. # Make the resource executable
  750. mode = ((os.stat(tempname).st_mode) | 0555) & 07777
  751. os.chmod(tempname, mode)
  752. def set_extraction_path(self, path):
  753. """Set the base path where resources will be extracted to, if needed.
  754. If you do not call this routine before any extractions take place, the
  755. path defaults to the return value of ``get_default_cache()``. (Which
  756. is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
  757. platform-specific fallbacks. See that routine's documentation for more
  758. details.)
  759. Resources are extracted to subdirectories of this path based upon
  760. information given by the ``IResourceProvider``. You may set this to a
  761. temporary directory, but then you must call ``cleanup_resources()`` to
  762. delete the extracted files when done. There is no guarantee that
  763. ``cleanup_resources()`` will be able to remove all extracted files.
  764. (Note: you may not change the extraction path for a given resource
  765. manager once resources have been extracted, unless you first call
  766. ``cleanup_resources()``.)
  767. """
  768. if self.cached_files:
  769. raise ValueError(
  770. "Can't change extraction path, files already extracted"
  771. )
  772. self.extraction_path = path
  773. def cleanup_resources(self, force=False):
  774. """
  775. Delete all extracted resource files and directories, returning a list
  776. of the file and directory names that could not be successfully removed.
  777. This function does not have any concurrency protection, so it should
  778. generally only be called when the extraction path is a temporary
  779. directory exclusive to a single process. This method is not
  780. automatically called; you must call it explicitly or register it as an
  781. ``atexit`` function if you wish to ensure cleanup of a temporary
  782. directory used for extractions.
  783. """
  784. # XXX
  785. def get_default_cache():
  786. """Determine the default cache location
  787. This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
  788. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
  789. "Application Data" directory. On all other systems, it's "~/.python-eggs".
  790. """
  791. try:
  792. return os.environ['PYTHON_EGG_CACHE']
  793. except KeyError:
  794. pass
  795. if os.name!='nt':
  796. return os.path.expanduser('~/.python-eggs')
  797. app_data = 'Application Data' # XXX this may be locale-specific!
  798. app_homes = [
  799. (('APPDATA',), None), # best option, should be locale-safe
  800. (('USERPROFILE',), app_data),
  801. (('HOMEDRIVE','HOMEPATH'), app_data),
  802. (('HOMEPATH',), app_data),
  803. (('HOME',), None),
  804. (('WINDIR',), app_data), # 95/98/ME
  805. ]
  806. for keys, subdir in app_homes:
  807. dirname = ''
  808. for key in keys:
  809. if key in os.environ:
  810. dirname = os.path.join(dirname, os.environ[key])
  811. else:
  812. break
  813. else:
  814. if subdir:
  815. dirname = os.path.join(dirname,subdir)
  816. return os.path.join(dirname, 'Python-Eggs')
  817. else:
  818. raise RuntimeError(
  819. "Please set the PYTHON_EGG_CACHE enviroment variable"
  820. )
  821. def safe_name(name):
  822. """Convert an arbitrary string to a standard distribution name
  823. Any runs of non-alphanumeric/. characters are replaced with a single '-'.
  824. """
  825. return re.sub('[^A-Za-z0-9.]+', '-', name)
  826. def safe_version(version):
  827. """Convert an arbitrary string to a standard version string
  828. Spaces become dots, and all other non-alphanumeric characters become
  829. dashes, with runs of multiple dashes condensed to a single dash.
  830. """
  831. version = version.replace(' ','.')
  832. return re.sub('[^A-Za-z0-9.]+', '-', version)
  833. def safe_extra(extra):
  834. """Convert an arbitrary string to a standard 'extra' name
  835. Any runs of non-alphanumeric characters are replaced with a single '_',
  836. and the result is always lowercased.
  837. """
  838. return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
  839. def to_filename(name):
  840. """Convert a project or version name to its filename-escaped form
  841. Any '-' characters are currently replaced with '_'.
  842. """
  843. return name.replace('-','_')
  844. class NullProvider:
  845. """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
  846. egg_name = None
  847. egg_info = None
  848. loader = None
  849. def __init__(self, module):
  850. self.loader = getattr(module, '__loader__', None)
  851. self.module_path = os.path.dirname(getattr(module, '__file__', ''))
  852. def get_resource_filename(self, manager, resource_name):
  853. return self._fn(self.module_path, resource_name)
  854. def get_resource_stream(self, manager, resource_name):
  855. return StringIO(self.get_resource_string(manager, resource_name))
  856. def get_resource_string(self, manager, resource_name):
  857. return self._get(self._fn(self.module_path, resource_name))
  858. def has_resource(self, resource_name):
  859. return self._has(self._fn(self.module_path, resource_name))
  860. def has_metadata(self, name):
  861. return self.egg_info and self._has(self._fn(self.egg_info,name))
  862. if sys.version_info <= (3,):
  863. def get_metadata(self, name):
  864. if not self.egg_info:
  865. return ""
  866. return self._get(self._fn(self.egg_info,name))
  867. else:
  868. def get_metadata(self, name):
  869. if not self.egg_info:
  870. return ""
  871. return self._get(self._fn(self.egg_info,name)).decode("utf-8")
  872. def get_metadata_lines(self, name):
  873. return yield_lines(self.get_metadata(name))
  874. def resource_isdir(self,resource_name):
  875. return self._isdir(self._fn(self.module_path, resource_name))
  876. def metadata_isdir(self,name):
  877. return self.egg_info and self._isdir(self._fn(self.egg_info,name))
  878. def resource_listdir(self,resource_name):
  879. return self._listdir(self._fn(self.module_path,resource_name))
  880. def metadata_listdir(self,name):
  881. if self.egg_info:
  882. return self._listdir(self._fn(self.egg_info,name))
  883. return []
  884. def run_script(self,script_name,namespace):
  885. script = 'scripts/'+script_name
  886. if not self.has_metadata(script):
  887. raise ResolutionError("No script named %r" % script_name)
  888. script_text = self.get_metadata(script).replace('\r\n','\n')
  889. script_text = script_text.replace('\r','\n')
  890. script_filename = self._fn(self.egg_info,script)
  891. namespace['__file__'] = script_filename
  892. if os.path.exists(script_filename):
  893. execfile(script_filename, namespace, namespace)
  894. else:
  895. from linecache import cache
  896. cache[script_filename] = (
  897. len(script_text), 0, script_text.split('\n'), script_filename
  898. )
  899. script_code = compile(script_text,script_filename,'exec')
  900. exec script_code in namespace, namespace
  901. def _has(self, path):
  902. raise NotImplementedError(
  903. "Can't perform this operation for unregistered loader type"
  904. )
  905. def _isdir(self, path):
  906. raise NotImplementedError(
  907. "Can't perform this operation for unregistered loader type"
  908. )
  909. def _listdir(self, path):
  910. raise NotImplementedError(
  911. "Can't perform this operation for unregistered loader type"
  912. )
  913. def _fn(self, base, resource_name):
  914. if resource_name:
  915. return os.path.join(base, *resource_name.split('/'))
  916. return base
  917. def _get(self, path):
  918. if hasattr(self.loader, 'get_data'):
  919. return self.loader.get_data(path)
  920. raise NotImplementedError(
  921. "Can't perform this operation for loaders without 'get_data()'"
  922. )
  923. register_loader_type(object, NullProvider)
  924. class EggProvider(NullProvider):
  925. """Provider based on a virtual filesystem"""
  926. def __init__(self,module):
  927. NullProvider.__init__(self,module)
  928. self._setup_prefix()
  929. def _setup_prefix(self):
  930. # we assume here that our metadata may be nested inside a "basket"
  931. # of multiple eggs; that's why we use module_path instead of .archive
  932. path = self.module_path
  933. old = None
  934. while path!=old:
  935. if path.lower().endswith('.egg'):
  936. self.egg_name = os.path.basename(path)
  937. self.egg_info = os.path.join(path, 'EGG-INFO')
  938. self.egg_root = path
  939. break
  940. old = path
  941. path, base = os.path.split(path)
  942. class DefaultProvider(EggProvider):
  943. """Provides access to package resources in the filesystem"""
  944. def _has(self, path):
  945. return os.path.exists(path)
  946. def _isdir(self,path):
  947. return os.path.isdir(path)
  948. def _listdir(self,path):
  949. return os.listdir(path)
  950. def get_resource_stream(self, manager, resource_name):
  951. return open(self._fn(self.module_path, resource_name), 'rb')
  952. def _get(self, path):
  953. stream = open(path, 'rb')
  954. try:
  955. return stream.read()
  956. finally:
  957. stream.close()
  958. register_loader_type(type(None), DefaultProvider)
  959. try:
  960. # CPython >=3.3
  961. import _frozen_importlib
  962. except ImportError:
  963. pass
  964. else:
  965. register_loader_type(_frozen_importlib.SourceFileLoader, DefaultProvider)
  966. class EmptyProvider(NullProvider):
  967. """Provider that returns nothing for all requests"""
  968. _isdir = _has = lambda self,path: False
  969. _get = lambda self,path: ''
  970. _listdir = lambda self,path: []
  971. module_path = None
  972. def __init__(self):
  973. pass
  974. empty_provider = EmptyProvider()
  975. class ZipProvider(EggProvider):
  976. """Resource support for zips and eggs"""
  977. eagers = None
  978. def __init__(self, module):
  979. EggProvider.__init__(self,module)
  980. self.zipinfo = zipimport._zip_directory_cache[self.loader.archive]
  981. self.zip_pre = self.loader.archive+os.sep
  982. def _zipinfo_name(self, fspath):
  983. # Convert a virtual filename (full path to file) into a zipfile subpath
  984. # usable with the zipimport directory cache for our target archive
  985. if fspath.startswith(self.zip_pre):
  986. return fspath[len(self.zip_pre):]
  987. raise AssertionError(
  988. "%s is not a subpath of %s" % (fspath,self.zip_pre)
  989. )
  990. def _parts(self,zip_path):
  991. # Convert a zipfile subpath into an egg-relative path part list
  992. fspath = self.zip_pre+zip_path # pseudo-fs path
  993. if fspath.startswith(self.egg_root+os.sep):
  994. return fspath[len(self.egg_root)+1:].split(os.sep)
  995. raise AssertionError(
  996. "%s is not a subpath of %s" % (fspath,self.egg_root)
  997. )
  998. def get_resource_filename(self, manager, resource_name):
  999. if not self.egg_name:
  1000. raise NotImplementedError(
  1001. "resource_filename() only supported for .egg, not .zip"
  1002. )
  1003. # no need to lock for extraction, since we use temp names
  1004. zip_path = self._resource_to_zip(resource_name)
  1005. eagers = self._get_eager_resources()
  1006. if '/'.join(self._parts(zip_path)) in eagers:
  1007. for name in eagers:
  1008. self._extract_resource(manager, self._eager_to_zip(name))
  1009. return self._extract_resource(manager, zip_path)
  1010. def _extract_resource(self, manager, zip_path):
  1011. if zip_path in self._index():
  1012. for name in self._index()[zip_path]:
  1013. last = self._extract_resource(
  1014. manager, os.path.join(zip_path, name)
  1015. )
  1016. return os.path.dirname(last) # return the extracted directory name
  1017. zip_stat = self.zipinfo[zip_path]
  1018. t,d,size = zip_stat[5], zip_stat[6], zip_stat[3]
  1019. date_time = (
  1020. (d>>9)+1980, (d>>5)&0xF, d&0x1F, # ymd
  1021. (t&0xFFFF)>>11, (t>>5)&0x3F, (t&0x1F) * 2, 0, 0, -1 # hms, etc.
  1022. )
  1023. timestamp = time.mktime(date_time)
  1024. try:
  1025. if not WRITE_SUPPORT:
  1026. raise IOError('"os.rename" and "os.unlink" are not supported '
  1027. 'on this platform')
  1028. real_path = manager.get_cache_path(
  1029. self.egg_name, self._parts(zip_path)
  1030. )
  1031. if os.path.isfile(real_path):
  1032. stat = os.stat(real_path)
  1033. if stat.st_size==size and stat.st_mtime==timestamp:
  1034. # size and stamp match, don't bother extracting
  1035. return real_path
  1036. outf, tmpnam = _mkstemp(".$extract", dir=os.path.dirname(real_path))
  1037. os.write(outf, self.loader.get_data(zip_path))
  1038. os.close(outf)
  1039. utime(tmpnam, (timestamp,timestamp))
  1040. manager.postprocess(tmpnam, real_path)
  1041. try:
  1042. rename(tmpnam, real_path)
  1043. except os.error:
  1044. if os.path.isfile(real_path):
  1045. stat = os.stat(real_path)
  1046. if stat.st_size==size and stat.st_mtime==timestamp:
  1047. # size and stamp match, somebody did it just ahead of
  1048. # us, so we're done
  1049. return real_path
  1050. elif os.name=='nt': # Windows, del old file and retry
  1051. unlink(real_path)
  1052. rename(tmpnam, real_path)
  1053. return real_path
  1054. raise
  1055. except os.error:
  1056. manager.extraction_error() # report a user-friendly error
  1057. return real_path
  1058. def _get_eager_resources(self):
  1059. if self.eagers is None:
  1060. eagers = []
  1061. for name in ('native_libs.txt', 'eager_resources.txt'):
  1062. if self.has_metadata(name):
  1063. eagers.extend(self.get_metada

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