PageRenderTime 68ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/pkg_resources.py

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