if self.feature_is_included(name)==<NUM_LIT:0>:<EOL><INDENT>descr = self.features[name].description<EOL>raise DistutilsOptionError(<EOL>descr + "<STR_LIT>"<EOL>)<EOL><DEDENT>self.features[name].include_in(self)<EOL>self._set_feature(name,<NUM_LIT:1>)<EOL>

Request inclusion of feature named 'name


for k,v in list(attrs.items()):<EOL><INDENT>include = getattr(self, '<STR_LIT>'+k, None)<EOL>if include:<EOL><INDENT>include(v)<EOL><DEDENT>else:<EOL><INDENT>self._include_misc(k,v)<EOL><DEDENT><DEDENT>

Add items to distribution that are named in keyword arguments

        For example, 'dist.exclude(py_modules=["x"])' would add 'x' to
        the distribution's 'py_modules' attribute, if it was not already
        there.

        Currently, this method only supports inclusion for attributes that are
        lists or tuples.  If you need to add support for adding to other
        attributes in this or a subclass, you can add an '_include_X' method,
        where 'X' is the name of the attribute.  The method will be called with
        the value passed to 'include()'.  So, 'dist.include(foo={"bar":"baz"})'
        will try to call 'dist._include_foo({"bar":"baz"})', which can then
        handle whatever special inclusion logic is needed.


pfx = package+'<STR_LIT:.>'<EOL>if self.packages:<EOL><INDENT>self.packages = [<EOL>p for p in self.packages<EOL>if p != package and not p.startswith(pfx)<EOL>]<EOL><DEDENT>if self.py_modules:<EOL><INDENT>self.py_modules = [<EOL>p for p in self.py_modules<EOL>if p != package and not p.startswith(pfx)<EOL>]<EOL><DEDENT>if self.ext_modules:<EOL><INDENT>self.ext_modules = [<EOL>p for p in self.ext_modules<EOL>if p.name != package and not p.name.startswith(pfx)<EOL>]<EOL><DEDENT>

Remove packages, modules, and extensions in named package


pfx = package+'<STR_LIT:.>'<EOL>for p in self.iter_distribution_names():<EOL><INDENT>if p==package or p.startswith(pfx):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>

Return true if 'exclude_package(package)' would do something


if not isinstance(value,sequence):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % (name, value)<EOL>)<EOL><DEDENT>try:<EOL><INDENT>old = getattr(self,name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % name<EOL>)<EOL><DEDENT>if old is not None and not isinstance(old,sequence):<EOL><INDENT>raise DistutilsSetupError(<EOL>name+"<STR_LIT>"<EOL>)<EOL><DEDENT>elif old:<EOL><INDENT>setattr(self,name,[item for item in old if item not in value])<EOL><DEDENT>

Handle 'exclude()' for list/tuple attrs without a special handler


if not isinstance(value,sequence):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % (name, value)<EOL>)<EOL><DEDENT>try:<EOL><INDENT>old = getattr(self,name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % name<EOL>)<EOL><DEDENT>if old is None:<EOL><INDENT>setattr(self,name,value)<EOL><DEDENT>elif not isinstance(old,sequence):<EOL><INDENT>raise DistutilsSetupError(<EOL>name+"<STR_LIT>"<EOL>)<EOL><DEDENT>else:<EOL><INDENT>setattr(self,name,old+[item for item in value if item not in old])<EOL><DEDENT>

Handle 'include()' for list/tuple attrs without a special handler


for k,v in list(attrs.items()):<EOL><INDENT>exclude = getattr(self, '<STR_LIT>'+k, None)<EOL>if exclude:<EOL><INDENT>exclude(v)<EOL><DEDENT>else:<EOL><INDENT>self._exclude_misc(k,v)<EOL><DEDENT><DEDENT>

Remove items from distribution that are named in keyword arguments

        For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
        the distribution's 'py_modules' attribute.  Excluding packages uses
        the 'exclude_package()' method, so all of the package's contained
        packages, modules, and extensions are also excluded.

        Currently, this method only supports exclusion from attributes that are
        lists or tuples.  If you need to add support for excluding from other
        attributes in this or a subclass, you can add an '_exclude_X' method,
        where 'X' is the name of the attribute.  The method will be called with
        the value passed to 'exclude()'.  So, 'dist.exclude(foo={"bar":"baz"})'
        will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
        handle whatever special exclusion logic is needed.


d = {}<EOL>for cmd,opts in list(self.command_options.items()):<EOL><INDENT>for opt,(src,val) in list(opts.items()):<EOL><INDENT>if src != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>opt = opt.replace('<STR_LIT:_>','<STR_LIT:->')<EOL>if val==<NUM_LIT:0>:<EOL><INDENT>cmdobj = self.get_command_obj(cmd)<EOL>neg_opt = self.negative_opt.copy()<EOL>neg_opt.update(getattr(cmdobj,'<STR_LIT>',{}))<EOL>for neg,pos in list(neg_opt.items()):<EOL><INDENT>if pos==opt:<EOL><INDENT>opt=neg<EOL>val=None<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif val==<NUM_LIT:1>:<EOL><INDENT>val = None<EOL><DEDENT>d.setdefault(cmd,{})[opt] = val<EOL><DEDENT><DEDENT>return d<EOL>

Return a '{cmd: {opt:val}}' map of all command-line options

        Option names are all long, but do not include the leading '--', and
        contain dashes rather than underscores.  If the option doesn't take
        an argument (e.g. '--quiet'), the 'val' is 'None'.

        Note that options provided by config files are intentionally excluded.


for pkg in self.packages or ():<EOL><INDENT>yield pkg<EOL><DEDENT>for module in self.py_modules or ():<EOL><INDENT>yield module<EOL><DEDENT>for ext in self.ext_modules or ():<EOL><INDENT>if isinstance(ext,tuple):<EOL><INDENT>name, buildinfo = ext<EOL><DEDENT>else:<EOL><INDENT>name = ext.name<EOL><DEDENT>if name.endswith('<STR_LIT>'):<EOL><INDENT>name = name[:-<NUM_LIT:6>]<EOL><DEDENT>yield name<EOL><DEDENT>

Yield all packages, modules, and extension names in distribution


import sys<EOL>if sys.version_info < (<NUM_LIT:3>,) or self.help_commands:<EOL><INDENT>return _Distribution.handle_display_options(self, option_order)<EOL><DEDENT>import io<EOL>if not isinstance(sys.stdout, io.TextIOWrapper):<EOL><INDENT>return _Distribution.handle_display_options(self, option_order)<EOL><DEDENT>if sys.stdout.encoding.lower() in ('<STR_LIT:utf-8>', '<STR_LIT:utf8>'):<EOL><INDENT>return _Distribution.handle_display_options(self, option_order)<EOL><DEDENT>encoding = sys.stdout.encoding<EOL>errors = sys.stdout.errors<EOL>newline = sys.platform != '<STR_LIT:win32>' and '<STR_LIT:\n>' or None<EOL>line_buffering = sys.stdout.line_buffering<EOL>sys.stdout = io.TextIOWrapper(<EOL>sys.stdout.detach(), '<STR_LIT:utf-8>', errors, newline, line_buffering)<EOL>try:<EOL><INDENT>return _Distribution.handle_display_options(self, option_order)<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout = io.TextIOWrapper(<EOL>sys.stdout.detach(), encoding, errors, newline, line_buffering)<EOL><DEDENT>

If there were any non-global "display-only" options
        (--help-commands or the metadata display options) on the command
        line, display the requested info and return true; else return
        false.


return self.available and self.standard<EOL>

Should this feature be included by default?


if not self.available:<EOL><INDENT>raise DistutilsPlatformError(<EOL>self.description+"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>dist.include(**self.extras)<EOL>for f in self.require_features:<EOL><INDENT>dist.include_feature(f)<EOL><DEDENT>

Ensure feature and its requirements are included in distribution

        You may override this in a subclass to perform additional operations on
        the distribution.  Note that this method may be called more than once
        per feature, and so should be idempotent.


dist.exclude(**self.extras)<EOL>if self.remove:<EOL><INDENT>for item in self.remove:<EOL><INDENT>dist.exclude_package(item)<EOL><DEDENT><DEDENT>

Ensure feature is excluded from distribution

        You may override this in a subclass to perform additional operations on
        the distribution.  This method will be called at most once per
        feature, and only after all included features have been asked to
        include themselves.


for item in self.remove:<EOL><INDENT>if not dist.has_contents_for(item):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (self.description, item, item)<EOL>)<EOL><DEDENT><DEDENT>

Verify that feature makes sense in context of distribution

        This method is called by the distribution just before it parses its
        command line.  It checks to ensure that the 'remove' attribute, if any,
        contains only valid package/module names that are present in the base
        distribution when 'setup()' is called.  You may override it in a
        subclass to perform any other required validation of the feature
        against a target distribution.


pyrex_impls = '<STR_LIT>', '<STR_LIT>'<EOL>for pyrex_impl in pyrex_impls:<EOL><INDENT>try:<EOL><INDENT>__import__(pyrex_impl, fromlist=['<STR_LIT>']).build_ext<EOL>return True<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return False<EOL>

Return True if Cython or Pyrex can be imported.


def pyx_to_c(source):<EOL><INDENT>if source.endswith('<STR_LIT>'):<EOL><INDENT>source = source[:-<NUM_LIT:4>] + '<STR_LIT>'<EOL><DEDENT>return source<EOL><DEDENT>self.sources = map(pyx_to_c, self.sources)<EOL>


from array import array<EOL>from dis import HAVE_ARGUMENT, EXTENDED_ARG<EOL>bytes = array('<STR_LIT:b>',code.co_code)<EOL>eof = len(code.co_code)<EOL>ptr = <NUM_LIT:0><EOL>extended_arg = <NUM_LIT:0><EOL>while ptr<eof:<EOL><INDENT>op = bytes[ptr]<EOL>if op>=HAVE_ARGUMENT:<EOL><INDENT>arg = bytes[ptr+<NUM_LIT:1>] + bytes[ptr+<NUM_LIT:2>]*<NUM_LIT> + extended_arg<EOL>ptr += <NUM_LIT:3><EOL>if op==EXTENDED_ARG:<EOL><INDENT>extended_arg = arg * <NUM_LIT><EOL>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>arg = None<EOL>ptr += <NUM_LIT:1><EOL><DEDENT>yield op,arg<EOL><DEDENT>

Yield '(op,arg)' pair for each operation in code object 'code


parts = module.split('<STR_LIT:.>')<EOL>while parts:<EOL><INDENT>part = parts.pop(<NUM_LIT:0>)<EOL>f, path, (suffix,mode,kind) = info = imp.find_module(part, paths)<EOL>if kind==PKG_DIRECTORY:<EOL><INDENT>parts = parts or ['<STR_LIT>']<EOL>paths = [path]<EOL><DEDENT>elif parts:<EOL><INDENT>raise ImportError("<STR_LIT>" % (parts,module))<EOL><DEDENT><DEDENT>return info<EOL>

Just like 'imp.find_module()', but with package support


def get_module_constant(module, symbol, default=-<NUM_LIT:1>, paths=None):

try:<EOL><INDENT>f, path, (suffix,mode,kind) = find_module(module,paths)<EOL><DEDENT>except ImportError:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>if kind==PY_COMPILED:<EOL><INDENT>f.read(<NUM_LIT:8>)   <EOL>code = marshal.load(f)<EOL><DEDENT>elif kind==PY_FROZEN:<EOL><INDENT>code = imp.get_frozen_object(module)<EOL><DEDENT>elif kind==PY_SOURCE:<EOL><INDENT>code = compile(f.read(), path, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if module not in sys.modules:<EOL><INDENT>imp.load_module(module,f,path,(suffix,mode,kind))<EOL><DEDENT>return getattr(sys.modules[module],symbol,None)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if f:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT>return extract_constant(code,symbol,default)<EOL>

Find 'module' by searching 'paths', and extract 'symbol'

    Return 'None' if 'module' does not exist on 'paths', or it does not define
    'symbol'.  If the module defines 'symbol' as a constant, return the
    constant.  Otherwise, return 'default'.


if symbol not in code.co_names:<EOL><INDENT>return None<EOL><DEDENT>name_idx = list(code.co_names).index(symbol)<EOL>STORE_NAME = <NUM_LIT><EOL>STORE_GLOBAL = <NUM_LIT><EOL>LOAD_CONST = <NUM_LIT:100><EOL>const = default<EOL>for op, arg in _iter_code(code):<EOL><INDENT>if op==LOAD_CONST:<EOL><INDENT>const = code.co_consts[arg]<EOL><DEDENT>elif arg==name_idx and (op==STORE_NAME or op==STORE_GLOBAL):<EOL><INDENT>return const<EOL><DEDENT>else:<EOL><INDENT>const = default<EOL><DEDENT><DEDENT>

Extract the constant value of 'symbol' from 'code'

    If the name 'symbol' is bound to a constant value by the Python code
    object 'code', return that value.  If 'symbol' is bound to an expression,
    return 'default'.  Otherwise, return 'None'.

    Return value is based on the first assignment to 'symbol'.  'symbol' must
    be a global, or at least a non-"fast" local in the code block.  That is,
    only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
    must be present in 'code.co_names'.


if self.requested_version is not None:<EOL><INDENT>return '<STR_LIT>' % (self.name,self.requested_version)<EOL><DEDENT>return self.name<EOL>

Return full package/distribution name, w/version


return self.attribute is None or self.format is None orstr(version)!="<STR_LIT>" and version >= self.requested_version<EOL>


def get_version(self, paths=None, default="<STR_LIT>"):

if self.attribute is None:<EOL><INDENT>try:<EOL><INDENT>f,p,i = find_module(self.module,paths)<EOL>if f: f.close()<EOL>return default<EOL><DEDENT>except ImportError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>v = get_module_constant(self.module,self.attribute,default,paths)<EOL>if v is not None and v is not default and self.format is not None:<EOL><INDENT>return self.format(v)<EOL><DEDENT>return v<EOL>

Get version number of installed module, 'None', or 'default'

        Search 'paths' for module.  If not found, return 'None'.  If found,
        return the extracted version attribute, or 'default' if no version
        attribute was specified, or the value cannot be determined without
        importing the module.  The version is formatted according to the
        requirement's version format (if any), unless it is 'None' or the
        supplied 'default'.


return self.get_version(paths) is not None<EOL>

Return true if dependency is present on 'paths


version = self.get_version(paths)<EOL>if version is None:<EOL><INDENT>return False<EOL><DEDENT>return self.version_ok(version)<EOL>

Return true if dependency is present and up-to-date on 'paths


plat = get_build_platform(); m = macosVersionString.match(plat)<EOL>if m is not None and sys.platform == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>plat = '<STR_LIT>' % ('<STR_LIT:.>'.join(_macosx_vers()[:<NUM_LIT:2>]), m.group(<NUM_LIT:3>))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass    <EOL><DEDENT><DEDENT>return plat<EOL>

Return this platform's maximum compatible version.

    distutils.util.get_platform() normally reports the minimum version
    of Mac OS X that would be required to *use* extensions produced by
    distutils.  But what we want when checking compatibility is to know the
    version of Mac OS X that we are *running*.  To allow usage of packages that
    explicitly require a newer version of Mac OS X, we must also know the
    current version of the OS.

    If this condition occurs for any other platform with a version in its
    platform strings, this function should be extended accordingly.


_provider_factories[loader_type] = provider_factory<EOL>

Register `provider_factory` to make providers for `loader_type`

    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
    and `provider_factory` is a function that, passed a *module* object,
    returns an ``IResourceProvider`` for that module.


if isinstance(moduleOrReq,Requirement):<EOL><INDENT>return working_set.find(moduleOrReq) or require(str(moduleOrReq))[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>module = sys.modules[moduleOrReq]<EOL><DEDENT>except KeyError:<EOL><INDENT>__import__(moduleOrReq)<EOL>module = sys.modules[moduleOrReq]<EOL><DEDENT>loader = getattr(module, '<STR_LIT>', None)<EOL>return _find_adapter(_provider_factories, loader)(module)<EOL>

Return an IResourceProvider for the named module or requirement


try:<EOL><INDENT>from distutils.util import get_platform<EOL><DEDENT>except ImportError:<EOL><INDENT>from sysconfig import get_platform<EOL><DEDENT>plat = get_platform()<EOL>if sys.platform == "<STR_LIT>" and not plat.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>version = _macosx_vers()<EOL>machine = os.uname()[<NUM_LIT:4>].replace("<STR_LIT:U+0020>", "<STR_LIT:_>")<EOL>return "<STR_LIT>" % (int(version[<NUM_LIT:0>]), int(version[<NUM_LIT:1>]),<EOL>_macosx_arch(machine))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return plat<EOL>

Return this platform's string for platform-specific distributions

    XXX Currently this is the same as ``distutils.util.get_platform()``, but it
    needs some hacks for Linux and Mac OS X.


if provided is None or required is None or provided==required:<EOL><INDENT>return True     <EOL><DEDENT>reqMac = macosVersionString.match(required)<EOL>if reqMac:<EOL><INDENT>provMac = macosVersionString.match(provided)<EOL>if not provMac:<EOL><INDENT>provDarwin = darwinVersionString.match(provided)<EOL>if provDarwin:<EOL><INDENT>dversion = int(provDarwin.group(<NUM_LIT:1>))<EOL>macosversion = "<STR_LIT>" % (reqMac.group(<NUM_LIT:1>), reqMac.group(<NUM_LIT:2>))<EOL>if dversion == <NUM_LIT:7> and macosversion >= "<STR_LIT>" ordversion == <NUM_LIT:8> and macosversion >= "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False    <EOL><DEDENT>if provMac.group(<NUM_LIT:1>) != reqMac.group(<NUM_LIT:1>) orprovMac.group(<NUM_LIT:3>) != reqMac.group(<NUM_LIT:3>):<EOL><INDENT>return False<EOL><DEDENT>if int(provMac.group(<NUM_LIT:2>)) > int(reqMac.group(<NUM_LIT:2>)):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>return False<EOL>

Can code for the `provided` platform run on the `required` platform?

    Returns true if either platform is ``None``, or the platforms are equal.

    XXX Needs compatibility checks for Linux and other unixy OSes.


ns = sys._getframe(<NUM_LIT:1>).f_globals<EOL>name = ns['<STR_LIT>']<EOL>ns.clear()<EOL>ns['<STR_LIT>'] = name<EOL>require(dist_spec)[<NUM_LIT:0>].run_script(script_name, ns)<EOL>

Locate distribution `dist_spec` and run its `script_name` script


if isinstance(dist,str): dist = Requirement.parse(dist)<EOL>if isinstance(dist,Requirement): dist = get_provider(dist)<EOL>if not isinstance(dist,Distribution):<EOL><INDENT>raise TypeError("<STR_LIT>", dist)<EOL><DEDENT>return dist<EOL>

Return a current distribution object for a Requirement or string


def load_entry_point(dist, group, name):

return get_distribution(dist).load_entry_point(group, name)<EOL>

Return `name` entry point of `group` for `dist` or raise ImportError


return get_distribution(dist).get_entry_map(group)<EOL>

Return the entry point map for `group`, or the full entry map


return get_distribution(dist).get_entry_info(group, name)<EOL>

Return the EntryPoint object for `group`+`name`, or ``None``


try:<EOL><INDENT>return os.environ['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if os.name!='<STR_LIT>':<EOL><INDENT>return os.path.expanduser('<STR_LIT>')<EOL><DEDENT>app_data = '<STR_LIT>'   <EOL>app_homes = [<EOL>(('<STR_LIT>',), None),       <EOL>(('<STR_LIT>',), app_data),<EOL>(('<STR_LIT>','<STR_LIT>'), app_data),<EOL>(('<STR_LIT>',), app_data),<EOL>(('<STR_LIT>',), None),<EOL>(('<STR_LIT>',), app_data),    <EOL>]<EOL>for keys, subdir in app_homes:<EOL><INDENT>dirname = '<STR_LIT>'<EOL>for key in keys:<EOL><INDENT>if key in os.environ:<EOL><INDENT>dirname = os.path.join(dirname, os.environ[key])<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if subdir:<EOL><INDENT>dirname = os.path.join(dirname,subdir)<EOL><DEDENT>return os.path.join(dirname, '<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>

Determine the default cache location

    This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
    Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
    "Application Data" directory.  On all other systems, it's "~/.python-eggs".


return re.sub('<STR_LIT>', '<STR_LIT:->', name)<EOL>

Convert an arbitrary string to a standard distribution name

    Any runs of non-alphanumeric/. characters are replaced with a single '-'.


version = version.replace('<STR_LIT:U+0020>','<STR_LIT:.>')<EOL>return re.sub('<STR_LIT>', '<STR_LIT:->', version)<EOL>

Convert an arbitrary string to a standard version string

    Spaces become dots, and all other non-alphanumeric characters become
    dashes, with runs of multiple dashes condensed to a single dash.


return re.sub('<STR_LIT>', '<STR_LIT:_>', extra).lower()<EOL>

Convert an arbitrary string to a standard 'extra' name

    Any runs of non-alphanumeric characters are replaced with a single '_',
    and the result is always lowercased.


return name.replace('<STR_LIT:->','<STR_LIT:_>')<EOL>

Convert a project or version name to its filename-escaped form

    Any '-' characters are currently replaced with '_'.


try:<EOL><INDENT>importer = sys.path_importer_cache[path_item]<EOL><DEDENT>except KeyError:<EOL><INDENT>for hook in sys.path_hooks:<EOL><INDENT>try:<EOL><INDENT>importer = hook(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>importer = None<EOL><DEDENT><DEDENT>sys.path_importer_cache.setdefault(path_item,importer)<EOL>if importer is None:<EOL><INDENT>try:<EOL><INDENT>importer = ImpWrapper(path_item)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return importer<EOL>

Retrieve a PEP 302 "importer" for the given path item

    If there is no importer, this returns a wrapper around the builtin import
    machinery.  The returned importer is only cached if it was created by a
    path hook.


_distribution_finders[importer_type] = distribution_finder<EOL>

Register `distribution_finder` to find distributions in sys.path items

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `distribution_finder` is a callable that, passed a path
    item and the importer instance, yields ``Distribution`` instances found on
    that path item.  See ``pkg_resources.find_on_path`` for an example.


importer = get_importer(path_item)<EOL>finder = _find_adapter(_distribution_finders, importer)<EOL>return finder(importer, path_item, only)<EOL>

Yield distributions accessible via `path_item`


global StringIO<EOL>try:<EOL><INDENT>from io import StringIO<EOL><DEDENT>except ImportError:<EOL><INDENT>from io import StringIO<EOL><DEDENT>return StringIO(*args,**kw)<EOL>

Thunk to load the real StringIO on demand


def find_on_path(importer, path_item, only=False):

path_item = _normalize_cached(path_item)<EOL>if os.path.isdir(path_item) and os.access(path_item, os.R_OK):<EOL><INDENT>if path_item.lower().endswith('<STR_LIT>'):<EOL><INDENT>yield Distribution.from_filename(<EOL>path_item, metadata=PathMetadata(<EOL>path_item, os.path.join(path_item,'<STR_LIT>')<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>for entry in os.listdir(path_item):<EOL><INDENT>lower = entry.lower()<EOL>if lower.endswith('<STR_LIT>') or lower.endswith('<STR_LIT>'):<EOL><INDENT>fullpath = os.path.join(path_item, entry)<EOL>if os.path.isdir(fullpath):<EOL><INDENT>metadata = PathMetadata(path_item, fullpath)<EOL><DEDENT>else:<EOL><INDENT>metadata = FileMetadata(fullpath)<EOL><DEDENT>yield Distribution.from_location(<EOL>path_item,entry,metadata,precedence=DEVELOP_DIST<EOL>)<EOL><DEDENT>elif not only and lower.endswith('<STR_LIT>'):<EOL><INDENT>for dist in find_distributions(os.path.join(path_item, entry)):<EOL><INDENT>yield dist<EOL><DEDENT><DEDENT>elif not only and lower.endswith('<STR_LIT>'):<EOL><INDENT>for line in open(os.path.join(path_item, entry)):<EOL><INDENT>if not line.strip(): continue<EOL>for item in find_distributions(os.path.join(path_item,line.rstrip())):<EOL><INDENT>yield item<EOL><DEDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>

Yield distributions accessible on a sys.path directory


_namespace_handlers[importer_type] = namespace_handler<EOL>

Register `namespace_handler` to declare namespace packages

    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
    handler), and `namespace_handler` is a callable like this::

        def namespace_handler(importer,path_entry,moduleName,module):
            # return a path_entry to use for child packages

    Namespace handlers are only called if the importer object has already
    agreed that it can handle the relevant path item, and they should only
    return a subpath if the module __path__ does not already contain an
    equivalent subpath.  For an example namespace handler, see
    ``pkg_resources.file_ns_handler``.


importer = get_importer(path_item)<EOL>if importer is None:<EOL><INDENT>return None<EOL><DEDENT>loader = importer.find_module(packageName)<EOL>if loader is None:<EOL><INDENT>return None<EOL><DEDENT>module = sys.modules.get(packageName)<EOL>if module is None:<EOL><INDENT>module = sys.modules[packageName] = types.ModuleType(packageName)<EOL>module.__path__ = []<EOL>_set_parent_ns(packageName)<EOL><DEDENT>elif not hasattr(module,'<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>", packageName)<EOL><DEDENT>handler = _find_adapter(_namespace_handlers, importer)<EOL>subpath = handler(importer, path_item, packageName, module)<EOL>if subpath is not None:<EOL><INDENT>path = module.__path__<EOL>path.append(subpath)<EOL>loader.load_module(packageName)<EOL>for path_item in path:<EOL><INDENT>if path_item not in module.__path__:<EOL><INDENT>module.__path__.append(path_item)<EOL><DEDENT><DEDENT><DEDENT>return subpath<EOL>

Ensure that named package includes a subpath of path_item (if needed)


imp.acquire_lock()<EOL>try:<EOL><INDENT>if packageName in _namespace_packages:<EOL><INDENT>return<EOL><DEDENT>path, parent = sys.path, None<EOL>if '<STR_LIT:.>' in packageName:<EOL><INDENT>parent = '<STR_LIT:.>'.join(packageName.split('<STR_LIT:.>')[:-<NUM_LIT:1>])<EOL>declare_namespace(parent)<EOL>if parent not in _namespace_packages:<EOL><INDENT>__import__(parent)<EOL><DEDENT>try:<EOL><INDENT>path = sys.modules[parent].__path__<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError("<STR_LIT>", parent)<EOL><DEDENT><DEDENT>_namespace_packages.setdefault(parent,[]).append(packageName)<EOL>_namespace_packages.setdefault(packageName,[])<EOL>for path_item in path:<EOL><INDENT>_handle_ns(packageName, path_item)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>imp.release_lock()<EOL><DEDENT>

Declare that package 'packageName' is a namespace package


imp.acquire_lock()<EOL>try:<EOL><INDENT>for package in _namespace_packages.get(parent,()):<EOL><INDENT>subpath = _handle_ns(package, path_item)<EOL>if subpath: fixup_namespace_packages(subpath,package)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>imp.release_lock()<EOL><DEDENT>

Ensure that previously-declared namespace packages include path_item


def file_ns_handler(importer, path_item, packageName, module):

subpath = os.path.join(path_item, packageName.split('<STR_LIT:.>')[-<NUM_LIT:1>])<EOL>normalized = _normalize_cached(subpath)<EOL>for item in module.__path__:<EOL><INDENT>if _normalize_cached(item)==normalized:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return subpath<EOL><DEDENT>

Compute an ns-package subpath for a filesystem or zipfile importer


return os.path.normcase(os.path.realpath(filename))<EOL>

Normalize a file/dir name for comparison purposes


if isinstance(strs,str):<EOL><INDENT>for s in strs.splitlines():<EOL><INDENT>s = s.strip()<EOL>if s and not s.startswith('<STR_LIT:#>'):     <EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for ss in strs:<EOL><INDENT>for s in yield_lines(ss):<EOL><INDENT>yield s<EOL><DEDENT><DEDENT><DEDENT>

Yield non-empty/non-comment lines of a ``basestring`` or sequence


parts = []<EOL>for part in _parse_version_parts(s.lower()):<EOL><INDENT>if part.startswith('<STR_LIT:*>'):<EOL><INDENT>while parts and parts[-<NUM_LIT:1>]=='<STR_LIT>':<EOL><INDENT>parts.pop()<EOL><DEDENT><DEDENT>parts.append(part)<EOL><DEDENT>return tuple(parts)<EOL>

Convert a version string to a chronologically-sortable key

    This is a rough cross between distutils' StrictVersion and LooseVersion;
    if you give it versions that would work with StrictVersion, then it behaves
    the same; otherwise it acts like a slightly-smarter LooseVersion. It is
    *possible* to create pathological version coding schemes that will fool
    this parser, but they should be very rare in practice.

    The returned value will be a tuple of strings.  Numeric portions of the
    version are padded to 8 digits so they will compare numerically, but
    without relying on how numbers compare relative to strings.  Dots are
    dropped, but dashes are retained.  Trailing zeros between alpha segments
    or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
    "2.4". Alphanumeric parts are lower-cased.

    The algorithm assumes that strings like "-" and any alpha string that
    alphabetically follows "final"  represents a "patch level".  So, "2.4-1"
    is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
    considered newer than "2.4-1", which in turn is newer than "2.4".

    Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
    come before "final" alphabetically) are assumed to be pre-release versions,
    so that the version "2.4" is considered newer than "2.4a1".

    Finally, to handle miscellaneous cases, the strings "pre", "preview", and
    "rc" are treated as if they were "c", i.e. as though they were release
    candidates, and therefore are not as new as a version string that does not
    contain them, and "dev" is replaced with an '@' so that it sorts lower than
    than any other pre-release tag.


<EOL>lines = iter(yield_lines(strs))<EOL>def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):<EOL><INDENT>items = []<EOL>while not TERMINATOR(line,p):<EOL><INDENT>if CONTINUE(line,p):<EOL><INDENT>try:<EOL><INDENT>line = next(lines); p = <NUM_LIT:0><EOL><DEDENT>except StopIteration:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>match = ITEM(line,p)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>"+item_name+"<STR_LIT>",line,"<STR_LIT>",line[p:])<EOL><DEDENT>items.append(match.group(*groups))<EOL>p = match.end()<EOL>match = COMMA(line,p)<EOL>if match:<EOL><INDENT>p = match.end() <EOL><DEDENT>elif not TERMINATOR(line,p):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>",line,"<STR_LIT>",line[p:]<EOL>)<EOL><DEDENT><DEDENT>match = TERMINATOR(line,p)<EOL>if match: p = match.end()   <EOL>return line, p, items<EOL><DEDENT>for line in lines:<EOL><INDENT>match = DISTRO(line)<EOL>if not match:<EOL><INDENT>raise ValueError("<STR_LIT>", line)<EOL><DEDENT>project_name = match.group(<NUM_LIT:1>)<EOL>p = match.end()<EOL>extras = []<EOL>match = OBRACKET(line,p)<EOL>if match:<EOL><INDENT>p = match.end()<EOL>line, p, extras = scan_list(<EOL>DISTRO, CBRACKET, line, p, (<NUM_LIT:1>,), "<STR_LIT>"<EOL>)<EOL><DEDENT>line, p, specs = scan_list(VERSION,LINE_END,line,p,(<NUM_LIT:1>,<NUM_LIT:2>),"<STR_LIT>")<EOL>specs = [(op,safe_version(val)) for op,val in specs]<EOL>yield Requirement(project_name, specs, extras)<EOL><DEDENT>

Yield ``Requirement`` objects for each specification in `strs`

    `strs` must be an instance of ``basestring``, or a (possibly-nested)
    iterable thereof.


if req.project_name == '<STR_LIT>':<EOL><INDENT>if not len(req.specs):<EOL><INDENT>return True<EOL><DEDENT>for comparator, version in req.specs:<EOL><INDENT>if comparator in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:>>']:<EOL><INDENT>if '<STR_LIT>' in version:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL><DEDENT>return False<EOL>

Return True when distribute wants to override a setuptools dependency.

    We want to override when the requirement is setuptools and the version is
    a variant of 0.6.


if not isinstance(cls,type):<EOL><INDENT>class cls(cls,object): pass<EOL>return cls.__mro__[<NUM_LIT:1>:]<EOL><DEDENT>return cls.__mro__<EOL>


for t in _get_mro(getattr(ob, '<STR_LIT>', type(ob))):<EOL><INDENT>if t in registry:<EOL><INDENT>return registry[t]<EOL><DEDENT><DEDENT>

Return an adapter factory for `ob` from `registry`


dirname = os.path.dirname(path)<EOL>if not os.path.isdir(dirname):<EOL><INDENT>os.makedirs(dirname)<EOL><DEDENT>

Ensure that the parent directory of `path` exists


section = None<EOL>content = []<EOL>for line in yield_lines(s):<EOL><INDENT>if line.startswith("<STR_LIT:[>"):<EOL><INDENT>if line.endswith("<STR_LIT:]>"):<EOL><INDENT>if section or content:<EOL><INDENT>yield section, content<EOL><DEDENT>section = line[<NUM_LIT:1>:-<NUM_LIT:1>].strip()<EOL>content = []<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>", line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>content.append(line)<EOL><DEDENT><DEDENT>yield section, content<EOL>

Split a string or iterable thereof into (section,content) pairs

    Each ``section`` is a stripped version of the section header ("[section]")
    and each ``content`` is a list of stripped lines excluding blank lines and
    comment-only lines.  If there are any such lines before the first section
    header, they're returned in a first ``section`` of ``None``.


Does the package's distribution contain the named metadata?


Yield named metadata resource as list of non-blank non-comment lines

       Leading and trailing whitespace is stripped from each line, and lines
       with ``#`` as the first non-blank character are omitted.


Is the named metadata a directory?  (like ``os.path.isdir()``)


List of metadata names in the directory (like ``os.listdir()``)


Execute the named script in the supplied namespace dictionary


Return a true filesystem path for `resource_name`

        `manager` must be an ``IResourceManager``


Return a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``


Return a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``


Does the package contain the named resource?


Is the named resource a directory?  (like ``os.path.isdir()``)


List of resource names in the directory (like ``os.listdir()``)


self.entries = []<EOL>self.entry_keys = {}<EOL>self.by_key = {}<EOL>self.callbacks = []<EOL>if entries is None:<EOL><INDENT>entries = sys.path<EOL><DEDENT>for entry in entries:<EOL><INDENT>self.add_entry(entry)<EOL><DEDENT>

Create working set from list of path entries (default=sys.path)


self.entry_keys.setdefault(entry, [])<EOL>self.entries.append(entry)<EOL>for dist in find_distributions(entry, True):<EOL><INDENT>self.add(dist, entry, False)<EOL><DEDENT>

Add a path item to ``.entries``, finding any distributions on it

        ``find_distributions(entry,True)`` is used to find distributions
        corresponding to the path entry, and they are added.  `entry` is
        always appended to ``.entries``, even if it is already present.
        (This is because ``sys.path`` can contain the same value more than
        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
        equal ``sys.path``.)


return self.by_key.get(dist.key) == dist<EOL>

True if `dist` is the active distribution for its project


dist = self.by_key.get(req.key)<EOL>if dist is not None and dist not in req:<EOL><INDENT>raise VersionConflict(dist,req)     <EOL><DEDENT>else:<EOL><INDENT>return dist<EOL><DEDENT>

Find a distribution matching requirement `req`

        If there is an active distribution for the requested project, this
        returns it as long as it meets the version requirement specified by
        `req`.  But, if there is an active distribution for the project and it
        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
        If there is no active distribution for the requested project, ``None``
        is returned.


def iter_entry_points(self, group, name=None):

for dist in self:<EOL><INDENT>entries = dist.get_entry_map(group)<EOL>if name is None:<EOL><INDENT>for ep in list(entries.values()):<EOL><INDENT>yield ep<EOL><DEDENT><DEDENT>elif name in entries:<EOL><INDENT>yield entries[name]<EOL><DEDENT><DEDENT>

Yield entry point objects from `group` matching `name`

        If `name` is None, yields all entry points in `group` from all
        distributions in the working set, otherwise only ones matching
        both `group` and `name` are yielded (in distribution order).


def run_script(self, requires, script_name):

ns = sys._getframe(<NUM_LIT:1>).f_globals<EOL>name = ns['<STR_LIT>']<EOL>ns.clear()<EOL>ns['<STR_LIT>'] = name<EOL>self.require(requires)[<NUM_LIT:0>].run_script(script_name, ns)<EOL>

Locate distribution for `requires` and run `script_name` script


seen = {}<EOL>for item in self.entries:<EOL><INDENT>if item not in self.entry_keys:<EOL><INDENT>continue<EOL><DEDENT>for key in self.entry_keys[item]:<EOL><INDENT>if key not in seen:<EOL><INDENT>seen[key]=<NUM_LIT:1><EOL>yield self.by_key[key]<EOL><DEDENT><DEDENT><DEDENT>

Yield distributions for non-duplicate projects in the working set

        The yield order is the order in which the items' path entries were
        added to the working set.


def add(self, dist, entry=None, insert=True, replace=False):

if insert:<EOL><INDENT>dist.insert_on(self.entries, entry)<EOL><DEDENT>if entry is None:<EOL><INDENT>entry = dist.location<EOL><DEDENT>keys = self.entry_keys.setdefault(entry,[])<EOL>keys2 = self.entry_keys.setdefault(dist.location,[])<EOL>if not replace and dist.key in self.by_key:<EOL><INDENT>return      <EOL><DEDENT>self.by_key[dist.key] = dist<EOL>if dist.key not in keys:<EOL><INDENT>keys.append(dist.key)<EOL><DEDENT>if dist.key not in keys2:<EOL><INDENT>keys2.append(dist.key)<EOL><DEDENT>self._added_new(dist)<EOL>

Add `dist` to working set, associated with `entry`

        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
        On exit from this routine, `entry` is added to the end of the working
        set's ``.entries`` (if it wasn't already present).

        `dist` is only added to the working set if it's for a project that
        doesn't already have a distribution in the set, unless `replace=True`.
        If it's added, any callbacks registered with the ``subscribe()`` method
        will be called.


def resolve(self, requirements, env=None, installer=None,<EOL>replacement=True, replace_conflicting=False):

requirements = list(requirements)[::-<NUM_LIT:1>]  <EOL>processed = {}  <EOL>best = {}  <EOL>to_activate = []<EOL>while requirements:<EOL><INDENT>req = requirements.pop(<NUM_LIT:0>)   <EOL>if _override_setuptools(req) and replacement:<EOL><INDENT>req = Requirement.parse('<STR_LIT>')<EOL><DEDENT>if req in processed:<EOL><INDENT>continue<EOL><DEDENT>dist = best.get(req.key)<EOL>if dist is None:<EOL><INDENT>dist = self.by_key.get(req.key)<EOL>if dist is None or (dist not in req and replace_conflicting):<EOL><INDENT>ws = self<EOL>if env is None:<EOL><INDENT>if dist is None:<EOL><INDENT>env = Environment(self.entries)<EOL><DEDENT>else:<EOL><INDENT>env = Environment([])<EOL>ws = WorkingSet([])<EOL><DEDENT><DEDENT>dist = best[req.key] = env.best_match(req, ws, installer)<EOL>if dist is None:<EOL><INDENT>raise DistributionNotFound(req)<EOL><DEDENT><DEDENT>to_activate.append(dist)<EOL><DEDENT>if dist not in req:<EOL><INDENT>raise VersionConflict(dist,req) <EOL><DEDENT>requirements.extend(dist.requires(req.extras)[::-<NUM_LIT:1>])<EOL>processed[req] = True<EOL><DEDENT>return to_activate<EOL>

List all distributions needed to (recursively) meet `requirements`

        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
        if supplied, should be an ``Environment`` instance.  If
        not supplied, it defaults to all distributions available within any
        entry or distribution in the working set.  `installer`, if supplied,
        will be invoked with each requirement that cannot be met by an
        already-installed distribution; it should return a ``Distribution`` or
        ``None``.

        Unless `replace_conflicting=True`, raises a VersionConflict exception if
        any requirements are found on the path that have the correct name but
        the wrong version.  Otherwise, if an `installer` is supplied it will be
        invoked to obtain the correct version of the requirement and activate
        it.


def find_plugins(self,<EOL>plugin_env, full_env=None, installer=None, fallback=True<EOL>):

plugin_projects = list(plugin_env)<EOL>plugin_projects.sort()  <EOL>error_info = {}<EOL>distributions = {}<EOL>if full_env is None:<EOL><INDENT>env = Environment(self.entries)<EOL>env += plugin_env<EOL><DEDENT>else:<EOL><INDENT>env = full_env + plugin_env<EOL><DEDENT>shadow_set = self.__class__([])<EOL>list(map(shadow_set.add, self))   <EOL>for project_name in plugin_projects:<EOL><INDENT>for dist in plugin_env[project_name]:<EOL><INDENT>req = [dist.as_requirement()]<EOL>try:<EOL><INDENT>resolvees = shadow_set.resolve(req, env, installer)<EOL><DEDENT>except ResolutionError as v:<EOL><INDENT>error_info[dist] = v    <EOL>if fallback:<EOL><INDENT>continue    <EOL><DEDENT>else:<EOL><INDENT>break       <EOL><DEDENT><DEDENT>else:<EOL><INDENT>list(map(shadow_set.add, resolvees))<EOL>distributions.update(dict.fromkeys(resolvees))<EOL>break<EOL><DEDENT><DEDENT><DEDENT>distributions = list(distributions)<EOL>distributions.sort()<EOL>return distributions, error_info<EOL>

Find all activatable distributions in `plugin_env`

        Example usage::

            distributions, errors = working_set.find_plugins(
                Environment(plugin_dirlist)
            )
            map(working_set.add, distributions)  # add plugins+libs to sys.path
            print 'Could not load', errors        # display errors

        The `plugin_env` should be an ``Environment`` instance that contains
        only distributions that are in the project's "plugin directory" or
        directories. The `full_env`, if supplied, should be an ``Environment``
        contains all currently-available distributions.  If `full_env` is not
        supplied, one is created automatically from the ``WorkingSet`` this
        method is called on, which will typically mean that every directory on
        ``sys.path`` will be scanned for distributions.

        `installer` is a standard installer callback as used by the
        ``resolve()`` method. The `fallback` flag indicates whether we should
        attempt to resolve older versions of a plugin if the newest version
        cannot be resolved.

        This method returns a 2-tuple: (`distributions`, `error_info`), where
        `distributions` is a list of the distributions found in `plugin_env`
        that were loadable, along with any other distributions that are needed
        to resolve their dependencies.  `error_info` is a dictionary mapping
        unloadable plugin distributions to an exception instance describing the
        error that occurred. Usually this will be a ``DistributionNotFound`` or
        ``VersionConflict`` instance.


needed = self.resolve(parse_requirements(requirements))<EOL>for dist in needed:<EOL><INDENT>self.add(dist)<EOL><DEDENT>return needed<EOL>

Ensure that distributions matching `requirements` are activated

        `requirements` must be a string or a (possibly-nested) sequence
        thereof, specifying the distributions and versions required.  The
        return value is a sequence of the distributions that needed to be
        activated to fulfill the requirements; all relevant distributions are
        included, even if they were already activated in this working set.


if callback in self.callbacks:<EOL><INDENT>return<EOL><DEDENT>self.callbacks.append(callback)<EOL>for dist in self:<EOL><INDENT>callback(dist)<EOL><DEDENT>

Invoke `callback` for all distributions (including existing ones)


def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):

self._distmap = {}<EOL>self._cache = {}<EOL>self.platform = platform<EOL>self.python = python<EOL>self.scan(search_path)<EOL>

Snapshot distributions available on a search path

        Any distributions found on `search_path` are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.

        `platform` is an optional string specifying the name of the platform
        that platform-specific distributions must be compatible with.  If
        unspecified, it defaults to the current platform.  `python` is an
        optional string naming the desired version of Python (e.g. ``'2.4'``);
        it defaults to the current version.

        You may explicitly set `platform` (and/or `python`) to ``None`` if you
        wish to map *all* distributions, not just those compatible with the
        running platform or Python version.


return (self.python is None or dist.py_version is None<EOL>or dist.py_version==self.python)and compatible_platforms(dist.platform,self.platform)<EOL>

Is distribution `dist` acceptable for this environment?

        The distribution must match the platform and python version
        requirements specified when this environment was created, or False
        is returned.


self._distmap[dist.key].remove(dist)<EOL>


if search_path is None:<EOL><INDENT>search_path = sys.path<EOL><DEDENT>for item in search_path:<EOL><INDENT>for dist in find_distributions(item):<EOL><INDENT>self.add(dist)<EOL><DEDENT><DEDENT>

Scan `search_path` for distributions usable in this environment

        Any distributions found are added to the environment.
        `search_path` should be a sequence of ``sys.path`` items.  If not
        supplied, ``sys.path`` is used.  Only distributions conforming to
        the platform/python version defined at initialization are added.


try:<EOL><INDENT>return self._cache[project_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>project_name = project_name.lower()<EOL>if project_name not in self._distmap:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>if project_name not in self._cache:<EOL><INDENT>dists = self._cache[project_name] = self._distmap[project_name]<EOL>_sort_dists(dists)<EOL><DEDENT>return self._cache[project_name]<EOL>

Return a newest-to-oldest list of distributions for `project_name`


if self.can_add(dist) and dist.has_version():<EOL><INDENT>dists = self._distmap.setdefault(dist.key,[])<EOL>if dist not in dists:<EOL><INDENT>dists.append(dist)<EOL>if dist.key in self._cache:<EOL><INDENT>_sort_dists(self._cache[dist.key])<EOL><DEDENT><DEDENT><DEDENT>

Add `dist` if we ``can_add()`` it and it isn't already added


def best_match(self, req, working_set, installer=None):

dist = working_set.find(req)<EOL>if dist is not None:<EOL><INDENT>return dist<EOL><DEDENT>for dist in self[req.key]:<EOL><INDENT>if dist in req:<EOL><INDENT>return dist<EOL><DEDENT><DEDENT>return self.obtain(req, installer)<EOL>

Find distribution best matching `req` and usable on `working_set`

        This calls the ``find(req)`` method of the `working_set` to see if a
        suitable distribution is already active.  (This may raise
        ``VersionConflict`` if an unsuitable version of the project is already
        active in the specified `working_set`.)  If a suitable distribution
        isn't active, this method returns the newest distribution in the
        environment that meets the ``Requirement`` in `req`.  If no suitable
        distribution is found, and `installer` is supplied, then the result of
        calling the environment's ``obtain(req, installer)`` method will be
        returned.


def obtain(self, requirement, installer=None):

if installer is not None:<EOL><INDENT>return installer(requirement)<EOL><DEDENT>

Obtain a distribution matching `requirement` (e.g. via download)

        Obtain a distro that matches requirement (e.g. via download).  In the
        base ``Environment`` class, this routine just returns
        ``installer(requirement)``, unless `installer` is None, in which case
        None is returned instead.  This method is a hook that allows subclasses
        to attempt other ways of obtaining a distribution before falling back
        to the `installer` argument.


for key in list(self._distmap.keys()):<EOL><INDENT>if self[key]: yield key<EOL><DEDENT>

Yield the unique project names of the available distributions


if isinstance(other,Distribution):<EOL><INDENT>self.add(other)<EOL><DEDENT>elif isinstance(other,Environment):<EOL><INDENT>for project in other:<EOL><INDENT>for dist in other[project]:<EOL><INDENT>self.add(dist)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % (other,))<EOL><DEDENT>return self<EOL>

In-place addition of a distribution or environment


new = self.__class__([], platform=None, python=None)<EOL>for env in self, other:<EOL><INDENT>new += env<EOL><DEDENT>return new<EOL>

Add an environment or distribution to an environment


def resource_exists(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).has_resource(resource_name)<EOL>


def resource_isdir(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).resource_isdir(<EOL>resource_name<EOL>)<EOL>

Is the named resource an existing directory?


def resource_filename(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_filename(<EOL>self, resource_name<EOL>)<EOL>

Return a true filesystem path for specified resource


def resource_stream(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_stream(<EOL>self, resource_name<EOL>)<EOL>

Return a readable file-like object for specified resource


def resource_string(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).get_resource_string(<EOL>self, resource_name<EOL>)<EOL>


def resource_listdir(self, package_or_requirement, resource_name):

return get_provider(package_or_requirement).resource_listdir(<EOL>resource_name<EOL>)<EOL>

List the contents of the named resource directory


old_exc = sys.exc_info()[<NUM_LIT:1>]<EOL>cache_path = self.extraction_path or get_default_cache()<EOL>err = ExtractionError(

Give an error message for problems extracting file(s)


def get_cache_path(self, archive_name, names=()):

extract_path = self.extraction_path or get_default_cache()<EOL>target_path = os.path.join(extract_path, archive_name+'<STR_LIT>', *names)<EOL>try:<EOL><INDENT>_bypass_ensure_directory(target_path)<EOL><DEDENT>except:<EOL><INDENT>self.extraction_error()<EOL><DEDENT>self.cached_files[target_path] = <NUM_LIT:1><EOL>return target_path<EOL>

Return absolute location in cache for `archive_name` and `names`

        The parent directory of the resulting path will be created if it does
        not already exist.  `archive_name` should be the base filename of the
        enclosing egg (which may not be the name of the enclosing zipfile!),
        including its ".egg" extension.  `names`, if provided, should be a
        sequence of path name parts "under" the egg's extraction location.

        This method should only be called by resource providers that need to
        obtain an extraction location, and only for names they intend to
        extract, as it tracks the generated names for possible cleanup later.


def postprocess(self, tempname, filename):

if os.name == '<STR_LIT>':<EOL><INDENT>mode = ((os.stat(tempname).st_mode) | <NUM_LIT>) & <NUM_LIT><EOL>os.chmod(tempname, mode)<EOL><DEDENT>

Perform any platform-specific postprocessing of `tempname`

        This is where Mac header rewrites should be done; other platforms don't
        have anything special they should do.

        Resource providers should call this method ONLY after successfully
        extracting a compressed resource.  They must NOT call it on resources
        that are already in the filesystem.

        `tempname` is the current (temporary) name of the file, and `filename`
        is the name it will be renamed to by the caller after this routine
        returns.


if self.cached_files:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self.extraction_path = path<EOL>

Set the base path where resources will be extracted to, if needed.

        If you do not call this routine before any extractions take place, the
        path defaults to the return value of ``get_default_cache()``.  (Which
        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
        platform-specific fallbacks.  See that routine's documentation for more
        details.)

        Resources are extracted to subdirectories of this path based upon
        information given by the ``IResourceProvider``.  You may set this to a
        temporary directory, but then you must call ``cleanup_resources()`` to
        delete the extracted files when done.  There is no guarantee that
        ``cleanup_resources()`` will be able to remove all extracted files.

        (Note: you may not change the extraction path for a given resource
        manager once resources have been extracted, unless you first call
        ``cleanup_resources()``.)


<EOL>

Delete all extracted resource files and directories, returning a list
of the file and directory names that could not be successfully removed.
This function does not have any concurrency protection, so it should
generally only be called when the extraction path is a temporary
directory exclusive to a single process.  This method is not
automatically called; you must call it explicitly or register it as an
``atexit`` function if you wish to ensure cleanup of a temporary
directory used for extractions.


self.zipinfo = zipimport._zip_directory_cache[importer.archive]<EOL>self.zip_pre = importer.archive+os.sep<EOL>self.loader = importer<EOL>if importer.prefix:<EOL><INDENT>self.module_path = os.path.join(importer.archive, importer.prefix)<EOL><DEDENT>else:<EOL><INDENT>self.module_path = importer.archive<EOL><DEDENT>self._setup_prefix()<EOL>

Create a metadata provider from a zipimporter


try:<EOL><INDENT>attrs = extras = ()<EOL>name,value = src.split('<STR_LIT:=>',<NUM_LIT:1>)<EOL>if '<STR_LIT:[>' in value:<EOL><INDENT>value,extras = value.split('<STR_LIT:[>',<NUM_LIT:1>)<EOL>req = Requirement.parse("<STR_LIT>"+extras)<EOL>if req.specs: raise ValueError<EOL>extras = req.extras<EOL><DEDENT>if '<STR_LIT::>' in value:<EOL><INDENT>value,attrs = value.split('<STR_LIT::>',<NUM_LIT:1>)<EOL>if not MODULE(attrs.rstrip()):<EOL><INDENT>raise ValueError<EOL><DEDENT>attrs = attrs.rstrip().split('<STR_LIT:.>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>",<EOL>src<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return cls(name.strip(), value.strip(), attrs, extras, dist)<EOL><DEDENT>

Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1,extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional


def parse_group(cls, group, lines, dist=None):

if not MODULE(group):<EOL><INDENT>raise ValueError("<STR_LIT>", group)<EOL><DEDENT>this = {}<EOL>for line in yield_lines(lines):<EOL><INDENT>ep = cls.parse(line, dist)<EOL>if ep.name in this:<EOL><INDENT>raise ValueError("<STR_LIT>", group, ep.name)<EOL><DEDENT>this[ep.name]=ep<EOL><DEDENT>return this<EOL>


if isinstance(data,dict):<EOL><INDENT>data = list(data.items())<EOL><DEDENT>else:<EOL><INDENT>data = split_sections(data)<EOL><DEDENT>maps = {}<EOL>for group, lines in data:<EOL><INDENT>if group is None:<EOL><INDENT>if not lines:<EOL><INDENT>continue<EOL><DEDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>group = group.strip()<EOL>if group in maps:<EOL><INDENT>raise ValueError("<STR_LIT>", group)<EOL><DEDENT>maps[group] = cls.parse_group(group, lines, dist)<EOL><DEDENT>return maps<EOL>


dm = self._dep_map<EOL>deps = []<EOL>deps.extend(dm.get(None,()))<EOL>for ext in extras:<EOL><INDENT>try:<EOL><INDENT>deps.extend(dm[safe_extra(ext)])<EOL><DEDENT>except KeyError:<EOL><INDENT>raise UnknownExtra(<EOL>"<STR_LIT>" % (self, ext)<EOL>)<EOL><DEDENT><DEDENT>return deps<EOL>

List of Requirements needed for this distro if `extras` are used


if path is None: path = sys.path<EOL>self.insert_on(path)<EOL>if path is sys.path:<EOL><INDENT>fixup_namespace_packages(self.location)<EOL>list(map(declare_namespace, self._get_metadata('<STR_LIT>')))<EOL><DEDENT>

Ensure distribution is importable on `path` (default=sys.path)


filename = "<STR_LIT>" % (<EOL>to_filename(self.project_name), to_filename(self.version),<EOL>self.py_version or PY_MAJOR<EOL>)<EOL>if self.platform:<EOL><INDENT>filename += '<STR_LIT:->'+self.platform<EOL><DEDENT>return filename<EOL>

Return what this distribution's standard .egg filename should be


if attr.startswith('<STR_LIT:_>'):<EOL><INDENT>raise AttributeError(attr)<EOL><DEDENT>return getattr(self._provider, attr)<EOL>

Delegate all unrecognized public attributes to .metadata provider


return Requirement.parse('<STR_LIT>' % (self.project_name, self.version))<EOL>

Return a ``Requirement`` that matches this distribution exactly


def load_entry_point(self, group, name):

ep = self.get_entry_info(group,name)<EOL>if ep is None:<EOL><INDENT>raise ImportError("<STR_LIT>" % ((group,name),))<EOL><DEDENT>return ep.load()<EOL>

Return the `name` entry point of `group` or raise ImportError


try:<EOL><INDENT>ep_map = self._ep_map<EOL><DEDENT>except AttributeError:<EOL><INDENT>ep_map = self._ep_map = EntryPoint.parse_map(<EOL>self._get_metadata('<STR_LIT>'), self<EOL>)<EOL><DEDENT>if group is not None:<EOL><INDENT>return ep_map.get(group,{})<EOL><DEDENT>return ep_map<EOL>

Return the entry point map for `group`, or the full entry map


return self.get_entry_map(group).get(name)<EOL>

Return the EntryPoint object for `group`+`name`, or ``None``


loc = loc or self.location<EOL>if self.project_name == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>version = self.version<EOL><DEDENT>except ValueError:<EOL><INDENT>version = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in version:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % str(self.location))<EOL><DEDENT><DEDENT>if not loc:<EOL><INDENT>return<EOL><DEDENT>if path is sys.path:<EOL><INDENT>self.check_version_conflict()<EOL><DEDENT>nloc = _normalize_cached(loc)<EOL>bdir = os.path.dirname(nloc)<EOL>npath= list(map(_normalize_cached, path))<EOL>bp = None<EOL>for p, item in enumerate(npath):<EOL><INDENT>if item==nloc:<EOL><INDENT>break<EOL><DEDENT>elif item==bdir and self.precedence==EGG_DIST:<EOL><INDENT>path.insert(p, loc)<EOL>npath.insert(p, nloc)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path.append(loc)<EOL>return<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>np = npath.index(nloc, p+<NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>del npath[np], path[np]<EOL>p = np  <EOL><DEDENT><DEDENT>return<EOL>

Insert self.location in path before its nearest parent directory


for attr in (<EOL>'<STR_LIT>', '<STR_LIT:version>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:location>',<EOL>'<STR_LIT>'<EOL>):<EOL><INDENT>kw.setdefault(attr, getattr(self,attr,None))<EOL><DEDENT>kw.setdefault('<STR_LIT>', self._provider)<EOL>return self.__class__(**kw)<EOL>

Copy this distribution, substituting in any changed keyword args


try:<EOL><INDENT>return self._pkg_info<EOL><DEDENT>except AttributeError:<EOL><INDENT>from email.parser import Parser<EOL>self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))<EOL>return self._pkg_info<EOL><DEDENT>


parts = requires_dist.split('<STR_LIT:;>', <NUM_LIT:1>) + ['<STR_LIT>']<EOL>distvers = parts[<NUM_LIT:0>].strip()<EOL>mark = parts[<NUM_LIT:1>].strip()<EOL>distvers = re.sub(self.EQEQ, r"<STR_LIT>", distvers)<EOL>distvers = distvers.replace('<STR_LIT:(>', '<STR_LIT>').replace('<STR_LIT:)>', '<STR_LIT>')<EOL>return (distvers, mark)<EOL>

Convert 'Foobar (1); baz' to ('Foobar ==1', 'baz')
        Split environment marker, add == prefix to version specifiers as
        necessary, and remove parenthesis.


from _markerlib import compile as compile_marker<EOL>dm = self.__dep_map = {None: []}<EOL>reqs = []<EOL>for req in self._parsed_pkg_info.get_all('<STR_LIT>') or []:<EOL><INDENT>distvers, mark = self._preparse_requirement(req)<EOL>parsed = next(parse_requirements(distvers))<EOL>parsed.marker_fn = compile_marker(mark)<EOL>reqs.append(parsed)<EOL><DEDENT>def reqs_for_extra(extra):<EOL><INDENT>for req in reqs:<EOL><INDENT>if req.marker_fn(override={'<STR_LIT>':extra}):<EOL><INDENT>yield req<EOL><DEDENT><DEDENT><DEDENT>common = frozenset(reqs_for_extra(None))<EOL>dm[None].extend(common)<EOL>for extra in self._parsed_pkg_info.get_all('<STR_LIT>') or []:<EOL><INDENT>extra = safe_extra(extra.strip())<EOL>dm[extra] = list(frozenset(reqs_for_extra(extra)) - common)<EOL><DEDENT>return dm<EOL>

Recompute this distribution's dependencies.


def __init__(self, project_name, specs, extras):

self.unsafe_name, project_name = project_name, safe_name(project_name)<EOL>self.project_name, self.key = project_name, project_name.lower()<EOL>index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]<EOL>index.sort()<EOL>self.specs = [(op,ver) for parsed,trans,op,ver in index]<EOL>self.index, self.extras = index, tuple(map(safe_extra,extras))<EOL>self.hashCmp = (<EOL>self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),<EOL>frozenset(self.extras)<EOL>)<EOL>self.__hash = hash(self.hashCmp)<EOL>

DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!


return dict(_VARS)<EOL>

Return copy of default PEP 385 globals dictionary.


try:<EOL><INDENT>return _cache[marker]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if not marker.strip():<EOL><INDENT>def marker_fn(environment=None, override=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>return True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>compiled_marker = compile_marker(parse_marker(marker))<EOL>def marker_fn(environment=None, override=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if override is None:<EOL><INDENT>override = {}<EOL><DEDENT>if environment is None:<EOL><INDENT>environment = default_environment()<EOL><DEDENT>environment.update(override)<EOL>return eval(compiled_marker, environment)<EOL><DEDENT><DEDENT>marker_fn.__doc__ = marker<EOL>_cache[marker] = marker_fn<EOL>return _cache[marker]<EOL>

Return compiled marker as a function accepting an environment dict.


if not isinstance(node, self.ALLOWED):<EOL><INDENT>raise SyntaxError('<STR_LIT>' %<EOL>(self.statement,<EOL>('<STR_LIT:U+0020>' * node.col_offset) + '<STR_LIT>'))<EOL><DEDENT>return ast.NodeTransformer.visit(self, node)<EOL>

Ensure statement only contains allowed nodes.


new_node = ast.Name("<STR_LIT>" % (node.value.id, node.attr), node.ctx)<EOL>return ast.copy_location(new_node, node)<EOL>


def options(self, parser, env=os.environ):

super(NoseExclude, self).options(parser, env)<EOL>env_dirs = []<EOL>if '<STR_LIT>' in env:<EOL><INDENT>exclude_dirs = env.get('<STR_LIT>','<STR_LIT>')<EOL>env_dirs.extend(exclude_dirs.split('<STR_LIT:;>'))<EOL><DEDENT>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>default=env_dirs,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", type="<STR_LIT:string>",<EOL>dest="<STR_LIT>",<EOL>default=env.get('<STR_LIT>', False),<EOL>help="<STR_LIT>")<EOL>

Define the command line options for the plugin.


super(NoseExclude, self).configure(options, conf)<EOL>self.exclude_dirs = {}<EOL>if options.exclude_dir_file:<EOL><INDENT>if not options.exclude_dirs:<EOL><INDENT>options.exclude_dirs = []<EOL><DEDENT>new_dirs = self._load_from_file(options.exclude_dir_file)<EOL>options.exclude_dirs.extend(new_dirs)<EOL><DEDENT>if not options.exclude_dirs:<EOL><INDENT>self.enabled = False<EOL>return<EOL><DEDENT>self.enabled = True<EOL>root = os.getcwd()<EOL>log.debug('<STR_LIT>' % root)<EOL>for exclude_param in options.exclude_dirs:<EOL><INDENT>for d in exclude_param.split('<STR_LIT:\n>'):<EOL><INDENT>d = d.strip()<EOL>abs_d = self._force_to_abspath(d)<EOL>if abs_d:<EOL><INDENT>self.exclude_dirs[abs_d] = True<EOL><DEDENT><DEDENT><DEDENT>exclude_str = "<STR_LIT>" % "<STR_LIT:U+002C>".join(self.exclude_dirs.keys())<EOL>log.debug(exclude_str)<EOL>

Configure plugin based on command line options


if dirname in self.exclude_dirs:<EOL><INDENT>log.debug("<STR_LIT>" % dirname)<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Check if directory is eligible for test discovery


return list(filter(os.path.exists,<EOL>list(map(os.path.expanduser, config_files))))<EOL>

Return path to any existing user config files


user = user_config_files()<EOL>if os.path.exists('<STR_LIT>'):<EOL><INDENT>return user + ['<STR_LIT>']<EOL><DEDENT>return user<EOL>

Return path to any existing user config files, plus any setup.cfg
    in the current working directory.


if val == <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>elif val == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>val = str(val)<EOL>if len(val) > <NUM_LIT:5>:<EOL><INDENT>return False<EOL><DEDENT>return val.upper() in ('<STR_LIT:1>', '<STR_LIT:0>', '<STR_LIT:F>', '<STR_LIT:T>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>

Does the value look like an on/off flag?


def configure(self, argv=None, doc=None):

env = self.env<EOL>if argv is None:<EOL><INDENT>argv = sys.argv<EOL><DEDENT>cfg_files = getattr(self, '<STR_LIT>', [])<EOL>options, args = self._parseArgs(argv, cfg_files)<EOL>if getattr(options, '<STR_LIT>', []):<EOL><INDENT>options, args = self._parseArgs(argv, options.files)<EOL><DEDENT>self.options = options<EOL>if args:<EOL><INDENT>self.testNames = args<EOL><DEDENT>if options.testNames is not None:<EOL><INDENT>self.testNames.extend(tolist(options.testNames))<EOL><DEDENT>if options.py3where is not None:<EOL><INDENT>if sys.version_info >= (<NUM_LIT:3>,):<EOL><INDENT>options.where = options.py3where<EOL><DEDENT><DEDENT>if not options.where:<EOL><INDENT>options.where = env.get('<STR_LIT>', None)<EOL><DEDENT>if not options.ignoreFiles:<EOL><INDENT>options.ignoreFiles = env.get('<STR_LIT>', [])<EOL><DEDENT>if not options.include:<EOL><INDENT>options.include = env.get('<STR_LIT>', [])<EOL><DEDENT>if not options.exclude:<EOL><INDENT>options.exclude = env.get('<STR_LIT>', [])<EOL><DEDENT>self.addPaths = options.addPaths<EOL>self.stopOnError = options.stopOnError<EOL>self.verbosity = options.verbosity<EOL>self.includeExe = options.includeExe<EOL>self.traverseNamespace = options.traverseNamespace<EOL>self.debug = options.debug<EOL>self.debugLog = options.debugLog<EOL>self.loggingConfig = options.loggingConfig<EOL>self.firstPackageWins = options.firstPackageWins<EOL>self.configureLogging()<EOL>if options.where is not None:<EOL><INDENT>self.configureWhere(options.where)<EOL><DEDENT>if options.testMatch:<EOL><INDENT>self.testMatch = re.compile(options.testMatch)<EOL><DEDENT>if options.ignoreFiles:<EOL><INDENT>self.ignoreFiles = list(map(re.compile, tolist(options.ignoreFiles)))<EOL>log.info("<STR_LIT>", options.ignoreFiles)<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>", self.ignoreFilesDefaultStrings)<EOL><DEDENT>if options.include:<EOL><INDENT>self.include = list(map(re.compile, tolist(options.include)))<EOL>log.info("<STR_LIT>", options.include)<EOL><DEDENT>if options.exclude:<EOL><INDENT>self.exclude = list(map(re.compile, tolist(options.exclude)))<EOL>log.info("<STR_LIT>", options.exclude)<EOL><DEDENT>if not options.showPlugins:<EOL><INDENT>self.plugins.configure(options, self)<EOL>self.plugins.begin()<EOL><DEDENT>

Configure the nose running environment. Execute configure before
        collecting tests with nose.TestCollector to enable output capture and
        other features.


if self.loggingConfig:<EOL><INDENT>from logging.config import fileConfig<EOL>fileConfig(self.loggingConfig)<EOL>return<EOL><DEDENT>format = logging.Formatter('<STR_LIT>')<EOL>if self.debugLog:<EOL><INDENT>handler = logging.FileHandler(self.debugLog)<EOL><DEDENT>else:<EOL><INDENT>handler = logging.StreamHandler(self.logStream)<EOL><DEDENT>handler.setFormatter(format)<EOL>logger = logging.getLogger('<STR_LIT>')<EOL>logger.propagate = <NUM_LIT:0><EOL>if handler not in logger.handlers:<EOL><INDENT>logger.addHandler(handler)<EOL><DEDENT>lvl = logging.WARNING<EOL>if self.verbosity >= <NUM_LIT:5>:<EOL><INDENT>lvl = <NUM_LIT:0><EOL><DEDENT>elif self.verbosity >= <NUM_LIT:4>:<EOL><INDENT>lvl = logging.DEBUG<EOL><DEDENT>elif self.verbosity >= <NUM_LIT:3>:<EOL><INDENT>lvl = logging.INFO<EOL><DEDENT>logger.setLevel(lvl)<EOL>if self.debug:<EOL><INDENT>debug_loggers = [ name for name in self.debug.split('<STR_LIT:U+002C>')<EOL>if name ]<EOL>for logger_name in debug_loggers:<EOL><INDENT>l = logging.getLogger(logger_name)<EOL>l.setLevel(logging.DEBUG)<EOL>if not l.handlers and not logger_name.startswith('<STR_LIT>'):<EOL><INDENT>l.addHandler(handler)<EOL><DEDENT><DEDENT><DEDENT>

Configure logging for nose, or optionally other packages. Any logger
        name may be set with the debug option, and that logger will be set to
        debug level and be assigned the same handler as the nose loggers, unless
        it already has a handler.


from nose.importer import add_path<EOL>self.workingDir = None<EOL>where = tolist(where)<EOL>warned = False<EOL>for path in where:<EOL><INDENT>if not self.workingDir:<EOL><INDENT>abs_path = absdir(path)<EOL>if abs_path is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % path)<EOL><DEDENT>log.info("<STR_LIT>", abs_path)<EOL>self.workingDir = abs_path<EOL>if self.addPaths andos.path.exists(os.path.join(abs_path, '<STR_LIT>')):<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>" % abs_path)<EOL>add_path(abs_path)<EOL><DEDENT>continue<EOL><DEDENT>if not warned:<EOL><INDENT>warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning)<EOL><DEDENT>self.testNames.append(path)<EOL><DEDENT>

Configure the working directory or directories for the test run.


self.__dict__.update(self._default)<EOL>


if self.parser:<EOL><INDENT>return self.parser<EOL><DEDENT>env = self.env<EOL>parser = self.parserClass(doc)<EOL>parser.add_option(<EOL>"<STR_LIT>","<STR_LIT>", action="<STR_LIT:store_true>",<EOL>dest="<STR_LIT:version>", default=False,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>",<EOL>dest="<STR_LIT>", default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:count>", dest="<STR_LIT>",<EOL>default=self.verbosity,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT:store>", dest="<STR_LIT>",<EOL>metavar='<STR_LIT>',<EOL>type="<STR_LIT:int>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>", const=<NUM_LIT:0>, dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT:-c>", "<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>dest="<STR_LIT>", metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % self.testMatchPat,<EOL>default=self.testMatchPat)<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT:store>", dest="<STR_LIT>", default=None,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>dest="<STR_LIT>", default=self.debug,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", dest="<STR_LIT>", action="<STR_LIT:store>",<EOL>default=self.debugLog, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>dest="<STR_LIT>", action="<STR_LIT:store>",<EOL>default=self.loggingConfig, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>default=self.stopOnError,<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>default=self.addPaths,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>default=self.includeExe,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT>", dest="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>default=self.traverseNamespace, dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>action="<STR_LIT:store_true>", default=False, dest="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>self.plugins.loadPlugins()<EOL>self.pluginOpts(parser)<EOL>self.parser = parser<EOL>return parser<EOL>


return self.getParser(doc).format_help()<EOL>


if not os.path.isabs(path):<EOL><INDENT>path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),<EOL>path)))<EOL><DEDENT>if path is None or not os.path.isdir(path):<EOL><INDENT>return None<EOL><DEDENT>return path<EOL>

Return absolute, normalized path to directory, if it exists; None
    otherwise.


orig = path<EOL>if where is None:<EOL><INDENT>where = os.getcwd()<EOL><DEDENT>if isinstance(where, list) or isinstance(where, tuple):<EOL><INDENT>for maybe_path in where:<EOL><INDENT>maybe_abs = absfile(path, maybe_path)<EOL>if maybe_abs is not None:<EOL><INDENT>return maybe_abs<EOL><DEDENT><DEDENT>return None<EOL><DEDENT>if not os.path.isabs(path):<EOL><INDENT>path = os.path.normpath(os.path.abspath(os.path.join(where, path)))<EOL><DEDENT>if path is None or not os.path.exists(path):<EOL><INDENT>if where != os.getcwd():<EOL><INDENT>path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),<EOL>orig)))<EOL><DEDENT><DEDENT>if path is None or not os.path.exists(path):<EOL><INDENT>return None<EOL><DEDENT>if os.path.isdir(path):<EOL><INDENT>init = os.path.join(path,'<STR_LIT>')<EOL>if os.path.isfile(init):<EOL><INDENT>return init<EOL><DEDENT><DEDENT>elif os.path.isfile(path):<EOL><INDENT>return path<EOL><DEDENT>return None<EOL>

Return absolute, normalized path to file (optionally in directory
    where), or None if the file can't be found either in where or the current
    working directory.


return (os.path.exists(name)<EOL>or os.path.dirname(name)<EOL>or name.endswith('<STR_LIT>')<EOL>or not ident_re.match(os.path.splitext(name)[<NUM_LIT:0>]))<EOL>

A name is file-like if it is a path that exists, or it has a
    directory part, or it ends in .py, or it isn't a legal python
    identifier.


try:<EOL><INDENT>return func.compat_co_firstlineno<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>return func.func_code.co_firstlineno<EOL><DEDENT>except AttributeError:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT><DEDENT>

Get the line number of a function. First looks for
    compat_co_firstlineno, then func_code.co_first_lineno.


obj_type = type(obj)<EOL>return obj_type in class_types or issubclass(obj_type, type)<EOL>

Is obj a class? Inspect's isclass is too liberal and returns True
    for objects that can't be subclasses of anything.


if os.path.isdir(path):<EOL><INDENT>end = os.path.basename(path)<EOL>if ident_re.match(end):<EOL><INDENT>for init in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if os.path.isfile(os.path.join(path, init)):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if sys.platform.startswith('<STR_LIT>') andos.path.isfile(os.path.join(path, '<STR_LIT>')):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Is this path a package directory?

>>> ispackage('nose')
True
>>> ispackage('unit_tests')
False
>>> ispackage('nose/plugins')
True
>>> ispackage('nose/loader.py')
False


return type(obj) == property<EOL>

Is this a property?

>>> class Foo:
...     def got(self):
...         return 2
...     def get(self):
...         return 1
...     get = property(get)

>>> isproperty(Foo.got)
False
>>> isproperty(Foo.get)
True


if relativeTo is None:<EOL><INDENT>relativeTo = os.getcwd()<EOL><DEDENT>path = os.path.join(relativeTo, os.sep.join(package.split('<STR_LIT:.>')))<EOL>suffixes = ('<STR_LIT>', '<STR_LIT>')<EOL>for suffix in suffixes:<EOL><INDENT>filename = path + suffix<EOL>if os.path.exists(filename):<EOL><INDENT>return filename<EOL><DEDENT><DEDENT>return None<EOL>

Find the python source file for a package, relative to a
    particular directory (defaults to current working directory if not
    given).


src_file = src(filename)<EOL>if not src_file.endswith('<STR_LIT>') and not ispackage(src_file):<EOL><INDENT>return None<EOL><DEDENT>base, ext = os.path.splitext(os.path.basename(src_file))<EOL>if base == '<STR_LIT>':<EOL><INDENT>mod_parts = []<EOL><DEDENT>else:<EOL><INDENT>mod_parts = [base]<EOL><DEDENT>path, part = os.path.split(os.path.split(src_file)[<NUM_LIT:0>])<EOL>while part:<EOL><INDENT>if ispackage(os.path.join(path, part)):<EOL><INDENT>mod_parts.append(part)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT>path, part = os.path.split(path)<EOL><DEDENT>mod_parts.reverse()<EOL>return '<STR_LIT:.>'.join(mod_parts)<EOL>

Find the full dotted package name for a given python source file
name. Returns None if the file is not a python source file.

>>> getpackage('foo.py')
'foo'
>>> getpackage('biff/baf.py')
'baf'
>>> getpackage('nose/util.py')
'nose.util'

Works for directories too.

>>> getpackage('nose')
'nose'
>>> getpackage('nose/plugins')
'nose.plugins'

And __init__ files stuck onto directories

>>> getpackage('nose/plugins/__init__.py')
'nose.plugins'

Absolute paths also work.

>>> path = os.path.abspath(os.path.join('nose', 'plugins'))
>>> getpackage(path)
'nose.plugins'


label_len = len(label) + <NUM_LIT:2><EOL>chunk = (<NUM_LIT> - label_len) // <NUM_LIT:2><EOL>out = '<STR_LIT>' % ('<STR_LIT:->' * chunk, label, '<STR_LIT:->' * chunk)<EOL>pad = <NUM_LIT> - len(out)<EOL>if pad > <NUM_LIT:0>:<EOL><INDENT>out = out + ('<STR_LIT:->' * pad)<EOL><DEDENT>return out<EOL>


parts = name.split('<STR_LIT:.>')<EOL>parts_copy = parts[:]<EOL>if module is None:<EOL><INDENT>while parts_copy:<EOL><INDENT>try:<EOL><INDENT>log.debug("<STR_LIT>", name)<EOL>module = __import__('<STR_LIT:.>'.join(parts_copy))<EOL>break<EOL><DEDENT>except ImportError:<EOL><INDENT>del parts_copy[-<NUM_LIT:1>]<EOL>if not parts_copy:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>parts = parts[<NUM_LIT:1>:]<EOL><DEDENT>obj = module<EOL>log.debug("<STR_LIT>", parts, name, obj, module)<EOL>for part in parts:<EOL><INDENT>obj = getattr(obj, part)<EOL><DEDENT>return obj<EOL>

Resolve a dotted name to a module and its parts. This is stolen
    wholesale from unittest.TestLoader.loadTestByName.

    >>> resolve_name('nose.util') #doctest: +ELLIPSIS
    <module 'nose.util' from...>
    >>> resolve_name('nose.util.resolve_name') #doctest: +ELLIPSIS
    <function resolve_name at...>


for name in names:<EOL><INDENT>func = getattr(obj, name, None)<EOL>if func is not None:<EOL><INDENT>if type(obj) == types.ModuleType:<EOL><INDENT>try:<EOL><INDENT>args, varargs, varkw, defaults = inspect.getargspec(func)<EOL><DEDENT>except TypeError:<EOL><INDENT>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>func = func.__call__<EOL><DEDENT>try:<EOL><INDENT>args, varargs, varkw, defaults =inspect.getargspec(func)<EOL>args.pop(<NUM_LIT:0>) <EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(name, obj))<EOL><DEDENT><DEDENT>if len(args):<EOL><INDENT>log.debug("<STR_LIT>", obj, name, obj)<EOL>return func(obj)<EOL><DEDENT><DEDENT>log.debug("<STR_LIT>", obj, name)<EOL>return func()<EOL><DEDENT><DEDENT>

Given a list of possible method names, try to run them with the
    provided object. Keep going until something works. Used to run
    setup/teardown methods for module, package, and function tests.


if filename is None:<EOL><INDENT>return filename<EOL><DEDENT>if sys.platform.startswith('<STR_LIT>') and filename.endswith('<STR_LIT>'):<EOL><INDENT>return '<STR_LIT:.>'.join((filename[:-<NUM_LIT:9>], '<STR_LIT>'))<EOL><DEDENT>base, ext = os.path.splitext(filename)<EOL>if ext in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return '<STR_LIT:.>'.join((base, '<STR_LIT>'))<EOL><DEDENT>return filename<EOL>

Find the python source file for a .pyc, .pyo or $py.class file on
    jython. Returns the filename provided if it is not a python source
    file.


def k(obj):<EOL><INDENT>if regex.search(obj):<EOL><INDENT>return (<NUM_LIT:1>, obj)<EOL><DEDENT>return (<NUM_LIT:0>, obj)<EOL><DEDENT>return k<EOL>

Sort key function factory that puts items that match a
    regular expression last.

    >>> from nose.config import Config
    >>> from nose.pyversion import sort_list
    >>> c = Config()
    >>> regex = c.testMatch
    >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py']
    >>> sort_list(entries, regex_last_key(regex))
    >>> entries
    ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test']


if val is None:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>val.extend([])<EOL>return val<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return re.split(r'<STR_LIT>', val)<EOL><DEDENT>except TypeError:<EOL><INDENT>return list(val)<EOL><DEDENT>

Convert a value that may be a list or a (possibly comma-separated)
    string into a list. The exception: None is returned as None, not [None].

    >>> tolist(["one", "two"])
    ['one', 'two']
    >>> tolist("hello")
    ['hello']
    >>> tolist("separate,values, with, commas,  spaces , are    ,ok")
    ['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok']


from nose.tools import make_decorator<EOL>def newfunc(*arg, **kw):<EOL><INDENT>return func(*arg, **kw)<EOL><DEDENT>newfunc = make_decorator(func)(newfunc)<EOL>newfunc.__module__ = module<EOL>return newfunc<EOL>

Make a function imported from module A appear as if it is located
in module B.

>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'

The original function is not modified.

>>> pprint.__module__
'pprint'

Calling the transplanted function calls the original.

>>> pp([1, 2])
[1, 2]
>>> pprint([1,2])
[1, 2]


class C(cls):<EOL><INDENT>pass<EOL><DEDENT>C.__module__ = module<EOL>C.__name__ = cls.__name__<EOL>return C<EOL>

Make a class appear to reside in `module`, rather than the module in which
it is actually defined.

>>> from nose.failure import Failure
>>> Failure.__module__
'nose.failure'
>>> Nf = transplant_class(Failure, __name__)
>>> Nf.__module__
'nose.util'
>>> Nf.__name__
'Failure'


def proxied_attribute(local_attr, proxied_attr, doc):

def fget(self):<EOL><INDENT>return getattr(getattr(self, local_attr), proxied_attr)<EOL><DEDENT>def fset(self, value):<EOL><INDENT>setattr(getattr(self, local_attr), proxied_attr, value)<EOL><DEDENT>def fdel(self):<EOL><INDENT>delattr(getattr(self, local_attr), proxied_attr)<EOL><DEDENT>return property(fget, fset, fdel, doc)<EOL>

Create a property that proxies attribute ``proxied_attr`` through
    the local attribute ``local_attr``.


return ((self.match.search(name)<EOL>or (self.include and<EOL>filter(None,<EOL>[inc.search(name) for inc in self.include])))<EOL>and ((not self.exclude)<EOL>or not filter(None,<EOL>[exc.search(name) for exc in self.exclude])<EOL>))<EOL>

Does the name match my requirements?

        To match, a name must match config.testMatch OR config.include
        and it must not match config.exclude


declared = getattr(cls, '<STR_LIT>', None)<EOL>if declared is not None:<EOL><INDENT>wanted = declared<EOL><DEDENT>else:<EOL><INDENT>wanted = (not cls.__name__.startswith('<STR_LIT:_>')<EOL>and (issubclass(cls, unittest.TestCase)<EOL>or self.matches(cls.__name__)))<EOL><DEDENT>plug_wants = self.plugins.wantClass(cls)        <EOL>if plug_wants is not None:<EOL><INDENT>log.debug("<STR_LIT>", cls, plug_wants)<EOL>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", cls, wanted)<EOL>return wanted<EOL>

Is the class a wanted test class?

        A class must be a unittest.TestCase subclass, or match test name
        requirements. Classes that start with _ are always excluded.


tail = op_basename(dirname)<EOL>if ispackage(dirname):<EOL><INDENT>wanted = (not self.exclude<EOL>or not filter(None,<EOL>[exc.search(tail) for exc in self.exclude]<EOL>))<EOL><DEDENT>else:<EOL><INDENT>wanted = (self.matches(tail)<EOL>or (self.config.srcDirs<EOL>and tail in self.config.srcDirs))<EOL><DEDENT>plug_wants = self.plugins.wantDirectory(dirname)<EOL>if plug_wants is not None:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>dirname, plug_wants)<EOL>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", dirname, wanted)<EOL>return wanted<EOL>

Is the directory a wanted test directory?

        All package directories match, so long as they do not match exclude.
        All other directories must match test requirements.


<EOL>base = op_basename(file)<EOL>ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles<EOL>if ignore_this.search(base) ]<EOL>if ignore_matches:<EOL><INDENT>log.debug('<STR_LIT>',<EOL>base) <EOL>return False<EOL><DEDENT>if not self.config.includeExe and os.access(file, os.X_OK):<EOL><INDENT>log.info('<STR_LIT>', file)<EOL>return False<EOL><DEDENT>dummy, ext = op_splitext(base)<EOL>pysrc = ext == '<STR_LIT>'<EOL>wanted = pysrc and self.matches(base) <EOL>plug_wants = self.plugins.wantFile(file)<EOL>if plug_wants is not None:<EOL><INDENT>log.debug("<STR_LIT>", file, plug_wants)<EOL>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", file, wanted)<EOL>return wanted<EOL>

Is the file a wanted test file?

        The file must be a python source file and match testMatch or
        include, and not match exclude. Files that match ignore are *never*
        wanted, regardless of plugin, testMatch, include or exclude settings.


try:<EOL><INDENT>if hasattr(function, '<STR_LIT>'):<EOL><INDENT>funcname = function.compat_func_name<EOL><DEDENT>else:<EOL><INDENT>funcname = function.__name__<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>declared = getattr(function, '<STR_LIT>', None)<EOL>if declared is not None:<EOL><INDENT>wanted = declared<EOL><DEDENT>else:<EOL><INDENT>wanted = not funcname.startswith('<STR_LIT:_>') and self.matches(funcname)<EOL><DEDENT>plug_wants = self.plugins.wantFunction(function)<EOL>if plug_wants is not None:<EOL><INDENT>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", function, wanted)<EOL>return wanted<EOL>


try:<EOL><INDENT>method_name = method.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>if method_name.startswith('<STR_LIT:_>'):<EOL><INDENT>return False<EOL><DEDENT>declared = getattr(method, '<STR_LIT>', None)<EOL>if declared is not None:<EOL><INDENT>wanted = declared<EOL><DEDENT>else:<EOL><INDENT>wanted = self.matches(method_name)<EOL><DEDENT>plug_wants = self.plugins.wantMethod(method)<EOL>if plug_wants is not None:<EOL><INDENT>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", method, wanted)<EOL>return wanted<EOL>


declared = getattr(module, '<STR_LIT>', None)<EOL>if declared is not None:<EOL><INDENT>wanted = declared<EOL><DEDENT>else:<EOL><INDENT>wanted = self.matches(module.__name__.split('<STR_LIT:.>')[-<NUM_LIT:1>])or module.__name__ == '<STR_LIT:__main__>'<EOL><DEDENT>plug_wants = self.plugins.wantModule(module)<EOL>if plug_wants is not None:<EOL><INDENT>wanted = plug_wants<EOL><DEDENT>log.debug("<STR_LIT>", module, wanted)<EOL>return wanted<EOL>

Is the module a test module?

        The tail of the module name must match test requirements. One exception:
        we always want __main__.


<EOL>log.debug('<STR_LIT>' % path)    <EOL>if not path:<EOL><INDENT>return []<EOL><DEDENT>added = []<EOL>parent = os.path.dirname(path)<EOL>if (parent<EOL>and os.path.exists(os.path.join(path, '<STR_LIT>'))):<EOL><INDENT>added.extend(add_path(parent, config))<EOL><DEDENT>elif not path in sys.path:<EOL><INDENT>log.debug("<STR_LIT>", path)<EOL>sys.path.insert(<NUM_LIT:0>, path)<EOL>added.append(path)<EOL><DEDENT>if config and config.srcDirs:<EOL><INDENT>for dirname in config.srcDirs:<EOL><INDENT>dirpath = os.path.join(path, dirname)<EOL>if os.path.isdir(dirpath):<EOL><INDENT>sys.path.insert(<NUM_LIT:0>, dirpath)<EOL>added.append(dirpath)<EOL><DEDENT><DEDENT><DEDENT>return added<EOL>

Ensure that the path, or the root of the current package (if
    path is in a package), is in sys.path.


<EOL>path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)<EOL>name_parts = fqname.split('<STR_LIT:.>')<EOL>if path_parts[-<NUM_LIT:1>].startswith('<STR_LIT>'):<EOL><INDENT>path_parts.pop()<EOL><DEDENT>path_parts = path_parts[:-(len(name_parts))]<EOL>dir_path = os.sep.join(path_parts)<EOL>return self.importFromDir(dir_path, fqname)<EOL>

Import a dotted-name package whose tail is at path. In other words,
        given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
        bar from path/to/foo/bar, returning bar.


dir = os.path.normpath(os.path.abspath(dir))<EOL>log.debug("<STR_LIT>", fqname, dir)<EOL>if fqname == '<STR_LIT:__main__>':<EOL><INDENT>return sys.modules[fqname]<EOL><DEDENT>if self.config.addPaths:<EOL><INDENT>add_path(dir, self.config)<EOL><DEDENT>path = [dir]<EOL>parts = fqname.split('<STR_LIT:.>')<EOL>part_fqname = '<STR_LIT>'<EOL>mod = parent = fh = None<EOL>for part in parts:<EOL><INDENT>if part_fqname == '<STR_LIT>':<EOL><INDENT>part_fqname = part<EOL><DEDENT>else:<EOL><INDENT>part_fqname = "<STR_LIT>" % (part_fqname, part)<EOL><DEDENT>try:<EOL><INDENT>acquire_lock()<EOL>log.debug("<STR_LIT>",<EOL>part, part_fqname, path)<EOL>fh, filename, desc = find_module(part, path)<EOL>old = sys.modules.get(part_fqname)<EOL>if old is not None:<EOL><INDENT>log.debug("<STR_LIT>", part_fqname, old)<EOL>if (self.sameModule(old, filename)<EOL>or (self.config.firstPackageWins and<EOL>getattr(old, '<STR_LIT>', None))):<EOL><INDENT>mod = old<EOL><DEDENT>else:<EOL><INDENT>del sys.modules[part_fqname]<EOL>mod = load_module(part_fqname, fh, filename, desc)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mod = load_module(part_fqname, fh, filename, desc)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if fh:<EOL><INDENT>fh.close()<EOL><DEDENT>release_lock()<EOL><DEDENT>if parent:<EOL><INDENT>setattr(parent, part, mod)<EOL><DEDENT>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>path = mod.__path__<EOL><DEDENT>parent = mod<EOL><DEDENT>return mod<EOL>

Import a module *only* from path, ignoring sys.path and
        reloading if the version in sys.modules is not the one we want.


try:<EOL><INDENT>afterTest = result.afterTest<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>afterTest(self.test)<EOL><DEDENT>

Called after test is complete (after result.stopTest)


try:<EOL><INDENT>beforeTest = result.beforeTest<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>beforeTest(self.test)<EOL><DEDENT>

Called before test is run (before result.startTest)


exc, exv, tb = sys.exc_info()<EOL>return (exc, exv, tb)<EOL>


return self.test.id()<EOL>


if hasattr(self.test, '<STR_LIT:address>'):<EOL><INDENT>return self.test.address()<EOL><DEDENT>else:<EOL><INDENT>return test_address(self.test)<EOL><DEDENT>

Return a round-trip name for this test, a name that can be
        fed back as input to loadTestByName and (assuming the same
        plugin configuration) result in the loading of this test.


if self.resultProxy:<EOL><INDENT>result = self.resultProxy(result, self)<EOL><DEDENT>try:<EOL><INDENT>try:<EOL><INDENT>self.beforeTest(result)<EOL>self.runTest(result)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>err = sys.exc_info()<EOL>result.addError(self, err)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self.afterTest(result)<EOL><DEDENT>

Modified run for the test wrapper.

        From here we don't call result.startTest or stopTest or
        addSuccess.  The wrapper calls addError/addFailure only if its
        own setup or teardown fails, or running the wrapped test fails
        (eg, if the wrapped "test" is not callable).

        Two additional methods are called, beforeTest and
        afterTest. These give plugins a chance to modify the wrapped
        test before it is called and do cleanup after it is
        called. They are called unconditionally.


test = self.test<EOL>plug_test = self.config.plugins.prepareTestCase(self)<EOL>if plug_test is not None:<EOL><INDENT>test = plug_test<EOL><DEDENT>test(result)<EOL>

Run the test. Plugins may alter the test by returning a
        value from prepareTestCase. The value must be callable and
        must accept one argument, the result instance.


if self.descriptor is not None:<EOL><INDENT>return test_address(self.descriptor)<EOL><DEDENT>else:<EOL><INDENT>return test_address(self.test)<EOL><DEDENT>


if self.setUpFunc:<EOL><INDENT>self.setUpFunc()<EOL><DEDENT>else:<EOL><INDENT>names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>try_run(self.test, names)<EOL><DEDENT>

Run any setup function attached to the test function


if self.tearDownFunc:<EOL><INDENT>self.tearDownFunc()<EOL><DEDENT>else:<EOL><INDENT>names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>try_run(self.test, names)<EOL><DEDENT>

Run any teardown function attached to the test function


if self.descriptor:<EOL><INDENT>return self.descriptor, self.arg<EOL><DEDENT>else:<EOL><INDENT>return self.test, self.arg<EOL><DEDENT>

Get the descriptors of the test function: the function and
        arguments that will be used to construct the test name. In
        most cases, this is the function itself and no arguments. For
        tests generated by generator functions, the original
        (generator) function and args passed to the generated function
        are returned.


if self.descriptor is not None:<EOL><INDENT>return test_address(self.descriptor)<EOL><DEDENT>else:<EOL><INDENT>return test_address(self.method)<EOL><DEDENT>


if self.descriptor:<EOL><INDENT>return self.descriptor, self.arg<EOL><DEDENT>else:<EOL><INDENT>return self.method, self.arg<EOL><DEDENT>

Get the descriptors of the test method: the method and
        arguments that will be used to construct the test name. In
        most cases, this is the method itself and no arguments. For
        tests generated by generator methods, the original
        (generator) method and args passed to the generated method
        or function are returned.


def decorate(newfunc):<EOL><INDENT>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>name = func.compat_func_name<EOL><DEDENT>else:<EOL><INDENT>name = func.__name__<EOL><DEDENT>newfunc.__dict__ = func.__dict__<EOL>newfunc.__doc__ = func.__doc__<EOL>newfunc.__module__ = func.__module__<EOL>if not hasattr(newfunc, '<STR_LIT>'):<EOL><INDENT>newfunc.compat_co_firstlineno = func.func_code.co_firstlineno<EOL><DEDENT>try:<EOL><INDENT>newfunc.__name__ = name<EOL><DEDENT>except TypeError:<EOL><INDENT>newfunc.compat_func_name = name<EOL><DEDENT>return newfunc<EOL><DEDENT>return decorate<EOL>

Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).


valid = '<STR_LIT>'.join([e.__name__ for e in exceptions])<EOL>def decorate(func):<EOL><INDENT>name = func.__name__<EOL>def newfunc(*arg, **kw):<EOL><INDENT>try:<EOL><INDENT>func(*arg, **kw)<EOL><DEDENT>except exceptions:<EOL><INDENT>pass<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>message = "<STR_LIT>" % (name, valid)<EOL>raise AssertionError(message)<EOL><DEDENT><DEDENT>newfunc = make_decorator(func)(newfunc)<EOL>return newfunc<EOL><DEDENT>return decorate<EOL>

Test must raise one of expected exceptions to pass.

    Example use::

      @raises(TypeError, ValueError)
      def test_raises_type_error():
          raise TypeError("This test passes")

      @raises(Exception)
      def test_that_fails_by_passing():
          pass

    If you want to test many assertions about exceptions in a single test,
    you may want to use `assert_raises` instead.


import pdb<EOL>import sys<EOL>stdout = sys.stdout<EOL>sys.stdout = sys.__stdout__<EOL>pdb.Pdb().set_trace(sys._getframe().f_back)<EOL>

Call pdb.set_trace in the calling frame, first restoring
    sys.stdout to the real output stream. Note that sys.stdout is NOT
    reset to whatever it was before the call once pdb is done!


def decorate(func):<EOL><INDENT>def newfunc(*arg, **kw):<EOL><INDENT>start = time.time()<EOL>func(*arg, **kw)<EOL>end = time.time()<EOL>if end - start > limit:<EOL><INDENT>raise TimeExpired("<STR_LIT>" % limit)<EOL><DEDENT><DEDENT>newfunc = make_decorator(func)(newfunc)<EOL>return newfunc<EOL><DEDENT>return decorate<EOL>

Test must finish within specified time limit to pass.

    Example use::

      @timed(.1)
      def test_that_fails():
          time.sleep(.2)


def decorate(func, setup=setup, teardown=teardown):<EOL><INDENT>if setup:<EOL><INDENT>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>_old_s = func.setup<EOL>def _s():<EOL><INDENT>setup()<EOL>_old_s()<EOL><DEDENT>func.setup = _s<EOL><DEDENT>else:<EOL><INDENT>func.setup = setup<EOL><DEDENT><DEDENT>if teardown:<EOL><INDENT>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>_old_t = func.teardown<EOL>def _t():<EOL><INDENT>_old_t()<EOL>teardown()<EOL><DEDENT>func.teardown = _t<EOL><DEDENT>else:<EOL><INDENT>func.teardown = teardown<EOL><DEDENT><DEDENT>return func<EOL><DEDENT>return decorate<EOL>

Decorator to add setup and/or teardown methods to a test function::

      @with_setup(setup, teardown)
      def test_something():
          " ... "

    Note that `with_setup` is useful *only* for test functions, not for test
    methods or inside of TestCase subclasses.


if not expr:<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>

Shorthand for assert. Saves 3 whole characters!


if not a == b:<EOL><INDENT>raise AssertionError(msg or "<STR_LIT>" % (a, b))<EOL><DEDENT>

Shorthand for 'assert a == b, "%r != %r" % (a, b)