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
  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_metadata_lines(name))
  1064. self.eagers = eagers
  1065. return self.eagers
  1066. def _index(self):
  1067. try:
  1068. return self._dirindex
  1069. except AttributeError:
  1070. ind = {}
  1071. for path in self.zipinfo:
  1072. parts = path.split(os.sep)
  1073. while parts:
  1074. parent = os.sep.join(parts[:-1])
  1075. if parent in ind:
  1076. ind[parent].append(parts[-1])
  1077. break
  1078. else:
  1079. ind[parent] = [parts.pop()]
  1080. self._dirindex = ind
  1081. return ind
  1082. def _has(self, fspath):
  1083. zip_path = self._zipinfo_name(fspath)
  1084. return zip_path in self.zipinfo or zip_path in self._index()
  1085. def _isdir(self,fspath):
  1086. return self._zipinfo_name(fspath) in self._index()
  1087. def _listdir(self,fspath):
  1088. return list(self._index().get(self._zipinfo_name(fspath), ()))
  1089. def _eager_to_zip(self,resource_name):
  1090. return self._zipinfo_name(self._fn(self.egg_root,resource_name))
  1091. def _resource_to_zip(self,resource_name):
  1092. return self._zipinfo_name(self._fn(self.module_path,resource_name))
  1093. register_loader_type(zipimport.zipimporter, ZipProvider)
  1094. class FileMetadata(EmptyProvider):
  1095. """Metadata handler for standalone PKG-INFO files
  1096. Usage::
  1097. metadata = FileMetadata("/path/to/PKG-INFO")
  1098. This provider rejects all data and metadata requests except for PKG-INFO,
  1099. which is treated as existing, and will be the contents of the file at
  1100. the provided location.
  1101. """
  1102. def __init__(self,path):
  1103. self.path = path
  1104. def has_metadata(self,name):
  1105. return name=='PKG-INFO'
  1106. def get_metadata(self,name):
  1107. if name=='PKG-INFO':
  1108. f = open(self.path,'rU')
  1109. metadata = f.read()
  1110. f.close()
  1111. return metadata
  1112. raise KeyError("No metadata except PKG-INFO is available")
  1113. def get_metadata_lines(self,name):
  1114. return yield_lines(self.get_metadata(name))
  1115. class PathMetadata(DefaultProvider):
  1116. """Metadata provider for egg directories
  1117. Usage::
  1118. # Development eggs:
  1119. egg_info = "/path/to/PackageName.egg-info"
  1120. base_dir = os.path.dirname(egg_info)
  1121. metadata = PathMetadata(base_dir, egg_info)
  1122. dist_name = os.path.splitext(os.path.basename(egg_info))[0]
  1123. dist = Distribution(basedir,project_name=dist_name,metadata=metadata)
  1124. # Unpacked egg directories:
  1125. egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
  1126. metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
  1127. dist = Distribution.from_filename(egg_path, metadata=metadata)
  1128. """
  1129. def __init__(self, path, egg_info):
  1130. self.module_path = path
  1131. self.egg_info = egg_info
  1132. class EggMetadata(ZipProvider):
  1133. """Metadata provider for .egg files"""
  1134. def __init__(self, importer):
  1135. """Create a metadata provider from a zipimporter"""
  1136. self.zipinfo = zipimport._zip_directory_cache[importer.archive]
  1137. self.zip_pre = importer.archive+os.sep
  1138. self.loader = importer
  1139. if importer.prefix:
  1140. self.module_path = os.path.join(importer.archive, importer.prefix)
  1141. else:
  1142. self.module_path = importer.archive
  1143. self._setup_prefix()
  1144. class ImpWrapper:
  1145. """PEP 302 Importer that wraps Python's "normal" import algorithm"""
  1146. def __init__(self, path=None):
  1147. self.path = path
  1148. def find_module(self, fullname, path=None):
  1149. subname = fullname.split(".")[-1]
  1150. if subname != fullname and self.path is None:
  1151. return None
  1152. if self.path is None:
  1153. path = None
  1154. else:
  1155. path = [self.path]
  1156. try:
  1157. file, filename, etc = imp.find_module(subname, path)
  1158. except ImportError:
  1159. return None
  1160. return ImpLoader(file, filename, etc)
  1161. class ImpLoader:
  1162. """PEP 302 Loader that wraps Python's "normal" import algorithm"""
  1163. def __init__(self, file, filename, etc):
  1164. self.file = file
  1165. self.filename = filename
  1166. self.etc = etc
  1167. def load_module(self, fullname):
  1168. try:
  1169. mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  1170. finally:
  1171. if self.file: self.file.close()
  1172. # Note: we don't set __loader__ because we want the module to look
  1173. # normal; i.e. this is just a wrapper for standard import machinery
  1174. return mod
  1175. def get_importer(path_item):
  1176. """Retrieve a PEP 302 "importer" for the given path item
  1177. If there is no importer, this returns a wrapper around the builtin import
  1178. machinery. The returned importer is only cached if it was created by a
  1179. path hook.
  1180. """
  1181. try:
  1182. importer = sys.path_importer_cache[path_item]
  1183. except KeyError:
  1184. for hook in sys.path_hooks:
  1185. try:
  1186. importer = hook(path_item)
  1187. except ImportError:
  1188. pass
  1189. else:
  1190. break
  1191. else:
  1192. importer = None
  1193. sys.path_importer_cache.setdefault(path_item,importer)
  1194. if importer is None:
  1195. try:
  1196. importer = ImpWrapper(path_item)
  1197. except ImportError:
  1198. pass
  1199. return importer
  1200. try:
  1201. from pkgutil import get_importer, ImpImporter
  1202. except ImportError:
  1203. pass # Python 2.3 or 2.4, use our own implementation
  1204. else:
  1205. ImpWrapper = ImpImporter # Python 2.5, use pkgutil's implementation
  1206. del ImpLoader, ImpImporter
  1207. _declare_state('dict', _distribution_finders = {})
  1208. def register_finder(importer_type, distribution_finder):
  1209. """Register `distribution_finder` to find distributions in sys.path items
  1210. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1211. handler), and `distribution_finder` is a callable that, passed a path
  1212. item and the importer instance, yields ``Distribution`` instances found on
  1213. that path item. See ``pkg_resources.find_on_path`` for an example."""
  1214. _distribution_finders[importer_type] = distribution_finder
  1215. def find_distributions(path_item, only=False):
  1216. """Yield distributions accessible via `path_item`"""
  1217. importer = get_importer(path_item)
  1218. finder = _find_adapter(_distribution_finders, importer)
  1219. return finder(importer, path_item, only)
  1220. def find_in_zip(importer, path_item, only=False):
  1221. metadata = EggMetadata(importer)
  1222. if metadata.has_metadata('PKG-INFO'):
  1223. yield Distribution.from_filename(path_item, metadata=metadata)
  1224. if only:
  1225. return # don't yield nested distros
  1226. for subitem in metadata.resource_listdir('/'):
  1227. if subitem.endswith('.egg'):
  1228. subpath = os.path.join(path_item, subitem)
  1229. for dist in find_in_zip(zipimport.zipimporter(subpath), subpath):
  1230. yield dist
  1231. register_finder(zipimport.zipimporter, find_in_zip)
  1232. def StringIO(*args, **kw):
  1233. """Thunk to load the real StringIO on demand"""
  1234. global StringIO
  1235. try:
  1236. from cStringIO import StringIO
  1237. except ImportError:
  1238. from StringIO import StringIO
  1239. return StringIO(*args,**kw)
  1240. def find_nothing(importer, path_item, only=False):
  1241. return ()
  1242. register_finder(object,find_nothing)
  1243. def find_on_path(importer, path_item, only=False):
  1244. """Yield distributions accessible on a sys.path directory"""
  1245. path_item = _normalize_cached(path_item)
  1246. if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
  1247. if path_item.lower().endswith('.egg'):
  1248. # unpacked egg
  1249. yield Distribution.from_filename(
  1250. path_item, metadata=PathMetadata(
  1251. path_item, os.path.join(path_item,'EGG-INFO')
  1252. )
  1253. )
  1254. else:
  1255. # scan for .egg and .egg-info in directory
  1256. for entry in os.listdir(path_item):
  1257. lower = entry.lower()
  1258. if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
  1259. fullpath = os.path.join(path_item, entry)
  1260. if os.path.isdir(fullpath):
  1261. # egg-info directory, allow getting metadata
  1262. metadata = PathMetadata(path_item, fullpath)
  1263. else:
  1264. metadata = FileMetadata(fullpath)
  1265. yield Distribution.from_location(
  1266. path_item,entry,metadata,precedence=DEVELOP_DIST
  1267. )
  1268. elif not only and lower.endswith('.egg'):
  1269. for dist in find_distributions(os.path.join(path_item, entry)):
  1270. yield dist
  1271. elif not only and lower.endswith('.egg-link'):
  1272. for line in open(os.path.join(path_item, entry)):
  1273. if not line.strip(): continue
  1274. for item in find_distributions(os.path.join(path_item,line.rstrip())):
  1275. yield item
  1276. break
  1277. register_finder(ImpWrapper,find_on_path)
  1278. try:
  1279. # CPython >=3.3
  1280. import _frozen_importlib
  1281. except ImportError:
  1282. pass
  1283. else:
  1284. register_finder(_frozen_importlib.FileFinder, find_on_path)
  1285. _declare_state('dict', _namespace_handlers={})
  1286. _declare_state('dict', _namespace_packages={})
  1287. def register_namespace_handler(importer_type, namespace_handler):
  1288. """Register `namespace_handler` to declare namespace packages
  1289. `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
  1290. handler), and `namespace_handler` is a callable like this::
  1291. def namespace_handler(importer,path_entry,moduleName,module):
  1292. # return a path_entry to use for child packages
  1293. Namespace handlers are only called if the importer object has already
  1294. agreed that it can handle the relevant path item, and they should only
  1295. return a subpath if the module __path__ does not already contain an
  1296. equivalent subpath. For an example namespace handler, see
  1297. ``pkg_resources.file_ns_handler``.
  1298. """
  1299. _namespace_handlers[importer_type] = namespace_handler
  1300. def _handle_ns(packageName, path_item):
  1301. """Ensure that named package includes a subpath of path_item (if needed)"""
  1302. importer = get_importer(path_item)
  1303. if importer is None:
  1304. return None
  1305. loader = importer.find_module(packageName)
  1306. if loader is None:
  1307. return None
  1308. module = sys.modules.get(packageName)
  1309. if module is None:
  1310. module = sys.modules[packageName] = types.ModuleType(packageName)
  1311. module.__path__ = []
  1312. _set_parent_ns(packageName)
  1313. elif not hasattr(module,'__path__'):
  1314. raise TypeError("Not a package:", packageName)
  1315. handler = _find_adapter(_namespace_handlers, importer)
  1316. subpath = handler(importer, path_item, packageName, module)
  1317. if subpath is not None:
  1318. path = module.__path__
  1319. path.append(subpath)
  1320. loader.load_module(packageName)
  1321. for path_item in path:
  1322. if path_item not in module.__path__:
  1323. module.__path__.append(path_item)
  1324. return subpath
  1325. def declare_namespace(packageName):
  1326. """Declare that package 'packageName' is a namespace package"""
  1327. imp.acquire_lock()
  1328. try:
  1329. if packageName in _namespace_packages:
  1330. return
  1331. path, parent = sys.path, None
  1332. if '.' in packageName:
  1333. parent = '.'.join(packageName.split('.')[:-1])
  1334. declare_namespace(parent)
  1335. if parent not in _namespace_packages:
  1336. __import__(parent)
  1337. try:
  1338. path = sys.modules[parent].__path__
  1339. except AttributeError:
  1340. raise TypeError("Not a package:", parent)
  1341. # Track what packages are namespaces, so when new path items are added,
  1342. # they can be updated
  1343. _namespace_packages.setdefault(parent,[]).append(packageName)
  1344. _namespace_packages.setdefault(packageName,[])
  1345. for path_item in path:
  1346. # Ensure all the parent's path items are reflected in the child,
  1347. # if they apply
  1348. _handle_ns(packageName, path_item)
  1349. finally:
  1350. imp.release_lock()
  1351. def fixup_namespace_packages(path_item, parent=None):
  1352. """Ensure that previously-declared namespace packages include path_item"""
  1353. imp.acquire_lock()
  1354. try:
  1355. for package in _namespace_packages.get(parent,()):
  1356. subpath = _handle_ns(package, path_item)
  1357. if subpath: fixup_namespace_packages(subpath,package)
  1358. finally:
  1359. imp.release_lock()
  1360. def file_ns_handler(importer, path_item, packageName, module):
  1361. """Compute an ns-package subpath for a filesystem or zipfile importer"""
  1362. subpath = os.path.join(path_item, packageName.split('.')[-1])
  1363. normalized = _normalize_cached(subpath)
  1364. for item in module.__path__:
  1365. if _normalize_cached(item)==normalized:
  1366. break
  1367. else:
  1368. # Only return the path if it's not already there
  1369. return subpath
  1370. register_namespace_handler(ImpWrapper,file_ns_handler)
  1371. register_namespace_handler(zipimport.zipimporter,file_ns_handler)
  1372. try:
  1373. # CPython >=3.3
  1374. import _frozen_importlib
  1375. except ImportError:
  1376. pass
  1377. else:
  1378. register_namespace_handler(_frozen_importlib.FileFinder, file_ns_handler)
  1379. def null_ns_handler(importer, path_item, packageName, module):
  1380. return None
  1381. register_namespace_handler(object,null_ns_handler)
  1382. def normalize_path(filename):
  1383. """Normalize a file/dir name for comparison purposes"""
  1384. return os.path.normcase(os.path.realpath(filename))
  1385. def _normalize_cached(filename,_cache={}):
  1386. try:
  1387. return _cache[filename]
  1388. except KeyError:
  1389. _cache[filename] = result = normalize_path(filename)
  1390. return result
  1391. def _set_parent_ns(packageName):
  1392. parts = packageName.split('.')
  1393. name = parts.pop()
  1394. if parts:
  1395. parent = '.'.join(parts)
  1396. setattr(sys.modules[parent], name, sys.modules[packageName])
  1397. def yield_lines(strs):
  1398. """Yield non-empty/non-comment lines of a ``basestring`` or sequence"""
  1399. if isinstance(strs,basestring):
  1400. for s in strs.splitlines():
  1401. s = s.strip()
  1402. if s and not s.startswith('#'): # skip blank lines/comments
  1403. yield s
  1404. else:
  1405. for ss in strs:
  1406. for s in yield_lines(ss):
  1407. yield s
  1408. LINE_END = re.compile(r"\s*(#.*)?$").match # whitespace and comment
  1409. CONTINUE = re.compile(r"\s*\\\s*(#.*)?$").match # line continuation
  1410. DISTRO = re.compile(r"\s*((\w|[-.])+)").match # Distribution or extra
  1411. VERSION = re.compile(r"\s*(<=?|>=?|==|!=)\s*((\w|[-.])+)").match # ver. info
  1412. COMMA = re.compile(r"\s*,").match # comma between items
  1413. OBRACKET = re.compile(r"\s*\[").match
  1414. CBRACKET = re.compile(r"\s*\]").match
  1415. MODULE = re.compile(r"\w+(\.\w+)*$").match
  1416. EGG_NAME = re.compile(
  1417. r"(?P<name>[^-]+)"
  1418. r"( -(?P<ver>[^-]+) (-py(?P<pyver>[^-]+) (-(?P<plat>.+))? )? )?",
  1419. re.VERBOSE | re.IGNORECASE
  1420. ).match
  1421. component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
  1422. replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
  1423. def _parse_version_parts(s):
  1424. for part in component_re.split(s):
  1425. part = replace(part,part)
  1426. if part in ['', '.']:
  1427. continue
  1428. if part[:1] in '0123456789':
  1429. yield part.zfill(8) # pad for numeric comparison
  1430. else:
  1431. yield '*'+part
  1432. yield '*final' # ensure that alpha/beta/candidate are before final
  1433. def parse_version(s):
  1434. """Convert a version string to a chronologically-sortable key
  1435. This is a rough cross between distutils' StrictVersion and LooseVersion;
  1436. if you give it versions that would work with StrictVersion, then it behaves
  1437. the same; otherwise it acts like a slightly-smarter LooseVersion. It is
  1438. *possible* to create pathological version coding schemes that will fool
  1439. this parser, but they should be very rare in practice.
  1440. The returned value will be a tuple of strings. Numeric portions of the
  1441. version are padded to 8 digits so they will compare numerically, but
  1442. without relying on how numbers compare relative to strings. Dots are
  1443. dropped, but dashes are retained. Trailing zeros between alpha segments
  1444. or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
  1445. "2.4". Alphanumeric parts are lower-cased.
  1446. The algorithm assumes that strings like "-" and any alpha string that
  1447. alphabetically follows "final" represents a "patch level". So, "2.4-1"
  1448. is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
  1449. considered newer than "2.4-1", which in turn is newer than "2.4".
  1450. Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
  1451. come before "final" alphabetically) are assumed to be pre-release versions,
  1452. so that the version "2.4" is considered newer than "2.4a1".
  1453. Finally, to handle miscellaneous cases, the strings "pre", "preview", and
  1454. "rc" are treated as if they were "c", i.e. as though they were release
  1455. candidates, and therefore are not as new as a version string that does not
  1456. contain them, and "dev" is replaced with an '@' so that it sorts lower than
  1457. than any other pre-release tag.
  1458. """
  1459. parts = []
  1460. for part in _parse_version_parts(s.lower()):
  1461. if part.startswith('*'):
  1462. # remove trailing zeros from each series of numeric parts
  1463. while parts and parts[-1]=='00000000':
  1464. parts.pop()
  1465. parts.append(part)
  1466. return tuple(parts)
  1467. class EntryPoint(object):
  1468. """Object representing an advertised importable object"""
  1469. def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
  1470. if not MODULE(module_name):
  1471. raise ValueError("Invalid module name", module_name)
  1472. self.name = name
  1473. self.module_name = module_name
  1474. self.attrs = tuple(attrs)
  1475. self.extras = Requirement.parse(("x[%s]" % ','.join(extras))).extras
  1476. self.dist = dist
  1477. def __str__(self):
  1478. s = "%s = %s" % (self.name, self.module_name)
  1479. if self.attrs:
  1480. s += ':' + '.'.join(self.attrs)
  1481. if self.extras:
  1482. s += ' [%s]' % ','.join(self.extras)
  1483. return s
  1484. def __repr__(self):
  1485. return "EntryPoint.parse(%r)" % str(self)
  1486. def load(self, require=True, env=None, installer=None):
  1487. if require: self.require(env, installer)
  1488. entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  1489. for attr in self.attrs:
  1490. try:
  1491. entry = getattr(entry,attr)
  1492. except AttributeError:
  1493. raise ImportError("%r has no %r attribute" % (entry,attr))
  1494. return entry
  1495. def require(self, env=None, installer=None):
  1496. if self.extras and not self.dist:
  1497. raise UnknownExtra("Can't require() without a distribution", self)
  1498. map(working_set.add,
  1499. working_set.resolve(self.dist.requires(self.extras),env,installer))
  1500. #@classmethod
  1501. def parse(cls, src, dist=None):
  1502. """Parse a single entry point from string `src`
  1503. Entry point syntax follows the form::
  1504. name = some.module:some.attr [extra1,extra2]
  1505. The entry name and module name are required, but the ``:attrs`` and
  1506. ``[extras]`` parts are optional
  1507. """
  1508. try:
  1509. attrs = extras = ()
  1510. name,value = src.split('=',1)
  1511. if '[' in value:
  1512. value,extras = value.split('[',1)
  1513. req = Requirement.parse("x["+extras)
  1514. if req.specs: raise ValueError
  1515. extras = req.extras
  1516. if ':' in value:
  1517. value,attrs = value.split(':',1)
  1518. if not MODULE(attrs.rstrip()):
  1519. raise ValueError
  1520. attrs = attrs.rstrip().split('.')
  1521. except ValueError:
  1522. raise ValueError(
  1523. "EntryPoint must be in 'name=module:attrs [extras]' format",
  1524. src
  1525. )
  1526. else:
  1527. return cls(name.strip(), value.strip(), attrs, extras, dist)
  1528. parse = classmethod(parse)
  1529. #@classmethod
  1530. def parse_group(cls, group, lines, dist=None):
  1531. """Parse an entry point group"""
  1532. if not MODULE(group):
  1533. raise ValueError("Invalid group name", group)
  1534. this = {}
  1535. for line in yield_lines(lines):
  1536. ep = cls.parse(line, dist)
  1537. if ep.name in this:
  1538. raise ValueError("Duplicate entry point", group, ep.name)
  1539. this[ep.name]=ep
  1540. return this
  1541. parse_group = classmethod(parse_group)
  1542. #@classmethod
  1543. def parse_map(cls, data, dist=None):
  1544. """Parse a map of entry point groups"""
  1545. if isinstance(data,dict):
  1546. data = data.items()
  1547. else:
  1548. data = split_sections(data)
  1549. maps = {}
  1550. for group, lines in data:
  1551. if group is None:
  1552. if not lines:
  1553. continue
  1554. raise ValueError("Entry points must be listed in groups")
  1555. group = group.strip()
  1556. if group in maps:
  1557. raise ValueError("Duplicate group name", group)
  1558. maps[group] = cls.parse_group(group, lines, dist)
  1559. return maps
  1560. parse_map = classmethod(parse_map)
  1561. def _remove_md5_fragment(location):
  1562. if not location:
  1563. return ''
  1564. parsed = urlparse(location)
  1565. if parsed[-1].startswith('md5='):
  1566. return urlunparse(parsed[:-1] + ('',))
  1567. return location
  1568. class Distribution(object):
  1569. """Wrap an actual or potential sys.path entry w/metadata"""
  1570. PKG_INFO = 'PKG-INFO'
  1571. def __init__(self,
  1572. location=None, metadata=None, project_name=None, version=None,
  1573. py_version=PY_MAJOR, platform=None, precedence = EGG_DIST
  1574. ):
  1575. self.project_name = safe_name(project_name or 'Unknown')
  1576. if version is not None:
  1577. self._version = safe_version(version)
  1578. self.py_version = py_version
  1579. self.platform = platform
  1580. self.location = location
  1581. self.precedence = precedence
  1582. self._provider = metadata or empty_provider
  1583. #@classmethod
  1584. def from_location(cls,location,basename,metadata=None,**kw):
  1585. project_name, version, py_version, platform = [None]*4
  1586. basename, ext = os.path.splitext(basename)
  1587. if ext.lower() in _distributionImpl:
  1588. # .dist-info gets much metadata differently
  1589. match = EGG_NAME(basename)
  1590. if match:
  1591. project_name, version, py_version, platform = match.group(
  1592. 'name','ver','pyver','plat'
  1593. )
  1594. cls = _distributionImpl[ext.lower()]
  1595. return cls(
  1596. location, metadata, project_name=project_name, version=version,
  1597. py_version=py_version, platform=platform, **kw
  1598. )
  1599. from_location = classmethod(from_location)
  1600. hashcmp = property(
  1601. lambda self: (
  1602. getattr(self,'parsed_version',()),
  1603. self.precedence,
  1604. self.key,
  1605. _remove_md5_fragment(self.location),
  1606. self.py_version,
  1607. self.platform
  1608. )
  1609. )
  1610. def __hash__(self): return hash(self.hashcmp)
  1611. def __lt__(self, other):
  1612. return self.hashcmp < other.hashcmp
  1613. def __le__(self, other):
  1614. return self.hashcmp <= other.hashcmp
  1615. def __gt__(self, other):
  1616. return self.hashcmp > other.hashcmp
  1617. def __ge__(self, other):
  1618. return self.hashcmp >= other.hashcmp
  1619. def __eq__(self, other):
  1620. if not isinstance(other, self.__class__):
  1621. # It's not a Distribution, so they are not equal
  1622. return False
  1623. return self.hashcmp == other.hashcmp
  1624. def __ne__(self, other):
  1625. return not self == other
  1626. # These properties have to be lazy so that we don't have to load any
  1627. # metadata until/unless it's actually needed. (i.e., some distributions
  1628. # may not know their name or version without loading PKG-INFO)
  1629. #@property
  1630. def key(self):
  1631. try:
  1632. return self._key
  1633. except AttributeError:
  1634. self._key = key = self.project_name.lower()
  1635. return key
  1636. key = property(key)
  1637. #@property
  1638. def parsed_version(self):
  1639. try:
  1640. return self._parsed_version
  1641. except AttributeError:
  1642. self._parsed_version = pv = parse_version(self.version)
  1643. return pv
  1644. parsed_version = property(parsed_version)
  1645. #@property
  1646. def version(self):
  1647. try:
  1648. return self._version
  1649. except AttributeError:
  1650. for line in self._get_metadata(self.PKG_INFO):
  1651. if line.lower().startswith('version:'):
  1652. self._version = safe_version(line.split(':',1)[1].strip())
  1653. return self._version
  1654. else:
  1655. raise ValueError(
  1656. "Missing 'Version:' header and/or %s file" % self.PKG_INFO, self
  1657. )
  1658. version = property(version)
  1659. #@property
  1660. def _dep_map(self):
  1661. try:
  1662. return self.__dep_map
  1663. except AttributeError:
  1664. dm = self.__dep_map = {None: []}
  1665. for name in 'requires.txt', 'depends.txt':
  1666. for extra,reqs in split_sections(self._get_metadata(name)):
  1667. if extra: extra = safe_extra(extra)
  1668. dm.setdefault(extra,[]).extend(parse_requirements(reqs))
  1669. return dm
  1670. _dep_map = property(_dep_map)
  1671. def requires(self,extras=()):
  1672. """List of Requirements needed for this distro if `extras` are used"""
  1673. dm = self._dep_map
  1674. deps = []
  1675. deps.extend(dm.get(None,()))
  1676. for ext in extras:
  1677. try:
  1678. deps.extend(dm[safe_extra(ext)])
  1679. except KeyError:
  1680. raise UnknownExtra(
  1681. "%s has no such extra feature %r" % (self, ext)
  1682. )
  1683. return deps
  1684. def _get_metadata(self,name):
  1685. if self.has_metadata(name):
  1686. for line in self.get_metadata_lines(name):
  1687. yield line
  1688. def activate(self,path=None):
  1689. """Ensure distribution is importable on `path` (default=sys.path)"""
  1690. if path is None: path = sys.path
  1691. self.insert_on(path)
  1692. if path is sys.path:
  1693. fixup_namespace_packages(self.location)
  1694. map(declare_namespace, self._get_metadata('namespace_packages.txt'))
  1695. def egg_name(self):
  1696. """Return what this distribution's standard .egg filename should be"""
  1697. filename = "%s-%s-py%s" % (
  1698. to_filename(self.project_name), to_filename(self.version),
  1699. self.py_version or PY_MAJOR
  1700. )
  1701. if self.platform:
  1702. filename += '-'+self.platform
  1703. return filename
  1704. def __repr__(self):
  1705. if self.location:
  1706. return "%s (%s)" % (self,self.location)
  1707. else:
  1708. return str(self)
  1709. def __str__(self):
  1710. try: version = getattr(self,'version',None)
  1711. except ValueError: version = None
  1712. version = version or "[unknown version]"
  1713. return "%s %s" % (self.project_name,version)
  1714. def __getattr__(self,attr):
  1715. """Delegate all unrecognized public attributes to .metadata provider"""
  1716. if attr.startswith('_'):
  1717. raise AttributeError,attr
  1718. return getattr(self._provider, attr)
  1719. #@classmethod
  1720. def from_filename(cls,filename,metadata=None, **kw):
  1721. return cls.from_location(
  1722. _normalize_cached(filename), os.path.basename(filename), metadata,
  1723. **kw
  1724. )
  1725. from_filename = classmethod(from_filename)
  1726. def as_requirement(self):
  1727. """Return a ``Requirement`` that matches this distribution exactly"""
  1728. return Requirement.parse('%s==%s' % (self.project_name, self.version))
  1729. def load_entry_point(self, group, name):
  1730. """Return the `name` entry point of `group` or raise ImportError"""
  1731. ep = self.get_entry_info(group,name)
  1732. if ep is None:
  1733. raise ImportError("Entry point %r not found" % ((group,name),))
  1734. return ep.load()
  1735. def get_entry_map(self, group=None):
  1736. """Return the entry point map for `group`, or the full entry map"""
  1737. try:
  1738. ep_map = self._ep_map
  1739. except AttributeError:
  1740. ep_map = self._ep_map = EntryPoint.parse_map(
  1741. self._get_metadata('entry_points.txt'), self
  1742. )
  1743. if group is not None:
  1744. return ep_map.get(group,{})
  1745. return ep_map
  1746. def get_entry_info(self, group, name):
  1747. """Return the EntryPoint object for `group`+`name`, or ``None``"""
  1748. return self.get_entry_map(group).get(name)
  1749. def insert_on(self, path, loc = None):
  1750. """Insert self.location in path before its nearest parent directory"""
  1751. loc = loc or self.location
  1752. if self.project_name == 'setuptools':
  1753. try:
  1754. version = self.version
  1755. except ValueError:
  1756. version = ''
  1757. if '0.7' in version:
  1758. raise ValueError(
  1759. "A 0.7-series setuptools cannot be installed "
  1760. "with distribute. Found one at %s" % str(self.location))
  1761. if not loc:
  1762. return
  1763. if path is sys.path:
  1764. self.check_version_conflict()
  1765. nloc = _normalize_cached(loc)
  1766. bdir = os.path.dirname(nloc)
  1767. npath= map(_normalize_cached, path)
  1768. bp = None
  1769. for p, item in enumerate(npath):
  1770. if item==nloc:
  1771. break
  1772. elif item==bdir and self.precedence==EGG_DIST:
  1773. # if it's an .egg, give it precedence over its directory
  1774. path.insert(p, loc)
  1775. npath.insert(p, nloc)
  1776. break
  1777. else:
  1778. path.append(loc)
  1779. return
  1780. # p is the spot where we found or inserted loc; now remove duplicates
  1781. while 1:
  1782. try:
  1783. np = npath.index(nloc, p+1)
  1784. except ValueError:
  1785. break
  1786. else:
  1787. del npath[np], path[np]
  1788. p = np # ha!
  1789. return
  1790. def check_version_conflict(self):
  1791. if self.key=='distribute':
  1792. return # ignore the inevitable setuptools self-conflicts :(
  1793. nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
  1794. loc = normalize_path(self.location)
  1795. for modname in self._get_metadata('top_level.txt'):
  1796. if (modname not in sys.modules or modname in nsp
  1797. or modname in _namespace_packages
  1798. ):
  1799. continue
  1800. if modname in ('pkg_resources', 'setuptools', 'site'):
  1801. continue
  1802. fn = getattr(sys.modules[modname], '__file__', None)
  1803. if fn and (normalize_path(fn).startswith(loc) or
  1804. fn.startswith(self.location)):
  1805. continue
  1806. issue_warning(
  1807. "Module %s was already imported from %s, but %s is being added"
  1808. " to sys.path" % (modname, fn, self.location),
  1809. )
  1810. def has_version(self):
  1811. try:
  1812. self.version
  1813. except ValueError:
  1814. issue_warning("Unbuilt egg for "+repr(self))
  1815. return False
  1816. return True
  1817. def clone(self,**kw):
  1818. """Copy this distribution, substituting in any changed keyword args"""
  1819. for attr in (
  1820. 'project_name', 'version', 'py_version', 'platform', 'location',
  1821. 'precedence'
  1822. ):
  1823. kw.setdefault(attr, getattr(self,attr,None))
  1824. kw.setdefault('metadata', self._provider)
  1825. return self.__class__(**kw)
  1826. #@property
  1827. def extras(self):
  1828. return [dep for dep in self._dep_map if dep]
  1829. extras = property(extras)
  1830. class DistInfoDistribution(Distribution):
  1831. """Wrap an actual or potential sys.path entry w/metadata, .dist-info style"""
  1832. PKG_INFO = 'METADATA'
  1833. EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
  1834. @property
  1835. def _parsed_pkg_info(self):
  1836. """Parse and cache metadata"""
  1837. try:
  1838. return self._pkg_info
  1839. except AttributeError:
  1840. from email.parser import Parser
  1841. self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
  1842. return self._pkg_info
  1843. @property
  1844. def _dep_map(self):
  1845. try:
  1846. return self.__dep_map
  1847. except AttributeError:
  1848. self.__dep_map = self._compute_dependencies()
  1849. return self.__dep_map
  1850. def _preparse_requirement(self, requires_dist):
  1851. """Convert 'Foobar (1); baz' to ('Foobar ==1', 'baz')
  1852. Split environment marker, add == prefix to version specifiers as
  1853. necessary, and remove parenthesis.
  1854. """
  1855. parts = requires_dist.split(';', 1) + ['']
  1856. distvers = parts[0].strip()
  1857. mark = parts[1].strip()
  1858. distvers = re.sub(self.EQEQ, r"\1==\2\3", distvers)
  1859. distvers = distvers.replace('(', '').replace(')', '')
  1860. return (distvers, mark)
  1861. def _compute_dependencies(self):
  1862. """Recompute this distribution's dependencies."""
  1863. from _markerlib import compile as compile_marker
  1864. dm = self.__dep_map = {None: []}
  1865. reqs = []
  1866. # Including any condition expressions
  1867. for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
  1868. distvers, mark = self._preparse_requirement(req)
  1869. parsed = parse_requirements(distvers).next()
  1870. parsed.marker_fn = compile_marker(mark)
  1871. reqs.append(parsed)
  1872. def reqs_for_extra(extra):
  1873. for req in reqs:
  1874. if req.marker_fn(override={'extra':extra}):
  1875. yield req
  1876. common = frozenset(reqs_for_extra(None))
  1877. dm[None].extend(common)
  1878. for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
  1879. extra = safe_extra(extra.strip())
  1880. dm[extra] = list(frozenset(reqs_for_extra(extra)) - common)
  1881. return dm
  1882. _distributionImpl = {'.egg': Distribution,
  1883. '.egg-info': Distribution,
  1884. '.dist-info': DistInfoDistribution }
  1885. def issue_warning(*args,**kw):
  1886. level = 1
  1887. g = globals()
  1888. try:
  1889. # find the first stack frame that is *not* code in
  1890. # the pkg_resources module, to use for the warning
  1891. while sys._getframe(level).f_globals is g:
  1892. level += 1
  1893. except ValueError:
  1894. pass
  1895. from warnings import warn
  1896. warn(stacklevel = level+1, *args, **kw)
  1897. def parse_requirements(strs):
  1898. """Yield ``Requirement`` objects for each specification in `strs`
  1899. `strs` must be an instance of ``basestring``, or a (possibly-nested)
  1900. iterable thereof.
  1901. """
  1902. # create a steppable iterator, so we can handle \-continuations
  1903. lines = iter(yield_lines(strs))
  1904. def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):
  1905. items = []
  1906. while not TERMINATOR(line,p):
  1907. if CONTINUE(line,p):
  1908. try:
  1909. line = lines.next(); p = 0
  1910. except StopIteration:
  1911. raise ValueError(
  1912. "\\ must not appear on the last nonblank line"
  1913. )
  1914. match = ITEM(line,p)
  1915. if not match:
  1916. raise ValueError("Expected "+item_name+" in",line,"at",line[p:])
  1917. items.append(match.group(*groups))
  1918. p = match.end()
  1919. match = COMMA(line,p)
  1920. if match:
  1921. p = match.end() # skip the comma
  1922. elif not TERMINATOR(line,p):
  1923. raise ValueError(
  1924. "Expected ',' or end-of-list in",line,"at",line[p:]
  1925. )
  1926. match = TERMINATOR(line,p)
  1927. if match: p = match.end() # skip the terminator, if any
  1928. return line, p, items
  1929. for line in lines:
  1930. match = DISTRO(line)
  1931. if not match:
  1932. raise ValueError("Missing distribution spec", line)
  1933. project_name = match.group(1)
  1934. p = match.end()
  1935. extras = []
  1936. match = OBRACKET(line,p)
  1937. if match:
  1938. p = match.end()
  1939. line, p, extras = scan_list(
  1940. DISTRO, CBRACKET, line, p, (1,), "'extra' name"
  1941. )
  1942. line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec")
  1943. specs = [(op,safe_version(val)) for op,val in specs]
  1944. yield Requirement(project_name, specs, extras)
  1945. def _sort_dists(dists):
  1946. tmp = [(dist.hashcmp,dist) for dist in dists]
  1947. tmp.sort()
  1948. dists[::-1] = [d for hc,d in tmp]
  1949. class Requirement:
  1950. def __init__(self, project_name, specs, extras):
  1951. """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
  1952. self.unsafe_name, project_name = project_name, safe_name(project_name)
  1953. self.project_name, self.key = project_name, project_name.lower()
  1954. index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]
  1955. index.sort()
  1956. self.specs = [(op,ver) for parsed,trans,op,ver in index]
  1957. self.index, self.extras = index, tuple(map(safe_extra,extras))
  1958. self.hashCmp = (
  1959. self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),
  1960. frozenset(self.extras)
  1961. )
  1962. self.__hash = hash(self.hashCmp)
  1963. def __str__(self):
  1964. specs = ','.join([''.join(s) for s in self.specs])
  1965. extras = ','.join(self.extras)
  1966. if extras: extras = '[%s]' % extras
  1967. return '%s%s%s' % (self.project_name, extras, specs)
  1968. def __eq__(self,other):
  1969. return isinstance(other,Requirement) and self.hashCmp==other.hashCmp
  1970. def __contains__(self,item):
  1971. if isinstance(item,Distribution):
  1972. if item.key <> self.key: return False
  1973. if self.index: item = item.parsed_version # only get if we need it
  1974. elif isinstance(item,basestring):
  1975. item = parse_version(item)
  1976. last = None
  1977. compare = lambda a, b: (a > b) - (a < b) # -1, 0, 1
  1978. for parsed,trans,op,ver in self.index:
  1979. action = trans[compare(item,parsed)] # Indexing: 0, 1, -1
  1980. if action=='F': return False
  1981. elif action=='T': return True
  1982. elif action=='+': last = True
  1983. elif action=='-' or last is None: last = False
  1984. if last is None: last = True # no rules encountered
  1985. return last
  1986. def __hash__(self):
  1987. return self.__hash
  1988. def __repr__(self): return "Requirement.parse(%r)" % str(self)
  1989. #@staticmethod
  1990. def parse(s, replacement=True):
  1991. reqs = list(parse_requirements(s))
  1992. if reqs:
  1993. if len(reqs) == 1:
  1994. founded_req = reqs[0]
  1995. # if asked for setuptools distribution
  1996. # and if distribute is installed, we want to give
  1997. # distribute instead
  1998. if _override_setuptools(founded_req) and replacement:
  1999. distribute = list(parse_requirements('distribute'))
  2000. if len(distribute) == 1:
  2001. return distribute[0]
  2002. return founded_req
  2003. else:
  2004. return founded_req
  2005. raise ValueError("Expected only one requirement", s)
  2006. raise ValueError("No requirements found", s)
  2007. parse = staticmethod(parse)
  2008. state_machine = {
  2009. # =><
  2010. '<' : '--T',
  2011. '<=': 'T-T',
  2012. '>' : 'F+F',
  2013. '>=': 'T+F',
  2014. '==': 'T..',
  2015. '!=': 'F++',
  2016. }
  2017. def _override_setuptools(req):
  2018. """Return True when distribute wants to override a setuptools dependency.
  2019. We want to override when the requirement is setuptools and the version is
  2020. a variant of 0.6.
  2021. """
  2022. if req.project_name == 'setuptools':
  2023. if not len(req.specs):
  2024. # Just setuptools: ok
  2025. return True
  2026. for comparator, version in req.specs:
  2027. if comparator in ['==', '>=', '>']:
  2028. if '0.7' in version:
  2029. # We want some setuptools not from the 0.6 series.
  2030. return False
  2031. return True
  2032. return False
  2033. def _get_mro(cls):
  2034. """Get an mro for a type or classic class"""
  2035. if not isinstance(cls,type):
  2036. class cls(cls,object): pass
  2037. return cls.__mro__[1:]
  2038. return cls.__mro__
  2039. def _find_adapter(registry, ob):
  2040. """Return an adapter factory for `ob` from `registry`"""
  2041. for t in _get_mro(getattr(ob, '__class__', type(ob))):
  2042. if t in registry:
  2043. return registry[t]
  2044. def ensure_directory(path):
  2045. """Ensure that the parent directory of `path` exists"""
  2046. dirname = os.path.dirname(path)
  2047. if not os.path.isdir(dirname):
  2048. os.makedirs(dirname)
  2049. def split_sections(s):
  2050. """Split a string or iterable thereof into (section,content) pairs
  2051. Each ``section`` is a stripped version of the section header ("[section]")
  2052. and each ``content`` is a list of stripped lines excluding blank lines and
  2053. comment-only lines. If there are any such lines before the first section
  2054. header, they're returned in a first ``section`` of ``None``.
  2055. """
  2056. section = None
  2057. content = []
  2058. for line in yield_lines(s):
  2059. if line.startswith("["):
  2060. if line.endswith("]"):
  2061. if section or content:
  2062. yield section, content
  2063. section = line[1:-1].strip()
  2064. content = []
  2065. else:
  2066. raise ValueError("Invalid section heading", line)
  2067. else:
  2068. content.append(line)
  2069. # wrap up last segment
  2070. yield section, content
  2071. def _mkstemp(*args,**kw):
  2072. from tempfile import mkstemp
  2073. old_open = os.open
  2074. try:
  2075. os.open = os_open # temporarily bypass sandboxing
  2076. return mkstemp(*args,**kw)
  2077. finally:
  2078. os.open = old_open # and then put it back
  2079. # Set up global resource manager (deliberately not state-saved)
  2080. _manager = ResourceManager()
  2081. def _initialize(g):
  2082. for name in dir(_manager):
  2083. if not name.startswith('_'):
  2084. g[name] = getattr(_manager, name)
  2085. _initialize(globals())
  2086. # Prepare the master working set and make the ``require()`` API available
  2087. _declare_state('object', working_set = WorkingSet())
  2088. try:
  2089. # Does the main program list any requirements?
  2090. from __main__ import __requires__
  2091. except ImportError:
  2092. pass # No: just use the default working set based on sys.path
  2093. else:
  2094. # Yes: ensure the requirements are met, by prefixing sys.path if necessary
  2095. try:
  2096. working_set.require(__requires__)
  2097. except VersionConflict: # try it without defaults already on sys.path
  2098. working_set = WorkingSet([]) # by starting with an empty path
  2099. for dist in working_set.resolve(
  2100. parse_requirements(__requires__), Environment()
  2101. ):
  2102. working_set.add(dist)
  2103. for entry in sys.path: # add any missing entries from sys.path
  2104. if entry not in working_set.entries:
  2105. working_set.add_entry(entry)
  2106. sys.path[:] = working_set.entries # then copy back to sys.path
  2107. require = working_set.require
  2108. iter_entry_points = working_set.iter_entry_points
  2109. add_activation_listener = working_set.subscribe
  2110. run_script = working_set.run_script
  2111. run_main = run_script # backward compatibility
  2112. # Activate all distributions already on sys.path, and ensure that
  2113. # all distributions added to the working set in the future (e.g. by
  2114. # calling ``require()``) will get activated as well.
  2115. add_activation_listener(lambda dist: dist.activate())
  2116. working_set.entries=[]; map(working_set.add_entry,sys.path) # match order