home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / pkg_resources.py < prev    next >
Encoding:
Python Source  |  2010-07-14  |  86.6 KB  |  2,694 lines

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