if run_frame is None:<EOL><INDENT>msg = "<STR_LIT>"<EOL>warnings.warn(msg)<EOL>if platform.python_implementation() == '<STR_LIT>':<EOL><INDENT>msg = "<STR_LIT>"<EOL>warnings.warn(msg)<EOL><DEDENT>return True<EOL><DEDENT>res = inspect.getouterframes(run_frame)[<NUM_LIT:2>]<EOL>caller, = res[:<NUM_LIT:1>]<EOL>info = inspect.getframeinfo(caller)<EOL>caller_module = caller.f_globals.get('<STR_LIT>', '<STR_LIT>')<EOL>return (<EOL>caller_module == '<STR_LIT>'<EOL>and info.function == '<STR_LIT>'<EOL>)<EOL>

Attempt to detect whether run() was called from setup() or by another
command.  If called by setup(), the parent caller will be the
'run_command' method in 'distutils.dist', and *its* caller will be
the 'run_commands' method.  If called any other way, the
immediate caller *might* be 'run_command', but it won't have been
called by 'run_commands'. Return True in that case or if a call stack
is unavailable. Return False otherwise.


contents = "<STR_LIT:\n>".join(contents)<EOL>contents = contents.encode("<STR_LIT:utf-8>")<EOL>with open(filename, "<STR_LIT:wb>") as f:  <EOL><INDENT>f.write(contents)<EOL><DEDENT>

Create a file with the specified name and write 'contents' (a
    sequence of strings without line terminators) to it.


def write_or_delete_file(self, what, filename, data, force=False):

if data:<EOL><INDENT>self.write_file(what, filename, data)<EOL><DEDENT>elif os.path.exists(filename):<EOL><INDENT>if data is None and not force:<EOL><INDENT>log.warn(<EOL>"<STR_LIT>", what, filename<EOL>)<EOL>return<EOL><DEDENT>else:<EOL><INDENT>self.delete_file(filename)<EOL><DEDENT><DEDENT>

Write `data` to `filename` or delete if empty

        If `data` is non-empty, this routine is the same as ``write_file()``.
        If `data` is empty but not ``None``, this is the same as calling
        ``delete_file(filename)`.  If `data` is ``None``, then this is a no-op
        unless `filename` exists, in which case a warning is issued about the
        orphaned file (if `force` is false), or deleted (if `force` is true).


def write_file(self, what, filename, data):

log.info("<STR_LIT>", what, filename)<EOL>if PY3:<EOL><INDENT>data = data.encode("<STR_LIT:utf-8>")<EOL><DEDENT>if not self.dry_run:<EOL><INDENT>f = open(filename, '<STR_LIT:wb>')<EOL>f.write(data)<EOL>f.close()<EOL><DEDENT>

Write `data` to `filename` (if not a dry run) after announcing it

        `what` is used in a log message to identify what is being written
        to the file.


log.info("<STR_LIT>", filename)<EOL>if not self.dry_run:<EOL><INDENT>os.unlink(filename)<EOL><DEDENT>

Delete `filename` (if not a dry run) after announcing it


manifest_filename = os.path.join(self.egg_info, "<STR_LIT>")<EOL>mm = manifest_maker(self.distribution)<EOL>mm.manifest = manifest_filename<EOL>mm.run()<EOL>self.filelist = mm.filelist<EOL>


self.files = list(filter(self._safe_path, self.files))<EOL>

Replace self.files with only safe paths

Because some owners of FileList manipulate the underlying
``files`` attribute directly, this method must be called to
repair those paths.


self.filelist._repair()<EOL>files = [self._manifest_normalize(f) for f in self.filelist.files]<EOL>msg = "<STR_LIT>" % self.manifest<EOL>self.execute(write_file, (self.manifest, files), msg)<EOL>

Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.


if cmd.egg_base == os.curdir:<EOL><INDENT>return<EOL><DEDENT>discovered = distutils.filelist.findall(cmd.egg_base)<EOL>resolved = (os.path.join(cmd.egg_base, path) for path in discovered)<EOL>self.filelist.allfiles.extend(resolved)<EOL>

Add paths for egg-info files for an external egg-base.

The egg-info files are written to egg-base. If egg-base is
outside the current working directory, this method
searchs the egg-base directory for files to include
in the manifest. Uses distutils.filelist.findall (which is
really the version monkeypatched in by setuptools/__init__.py)
to perform the search.

Since findall records relative paths, prefix the returned
paths with cmd.egg_base, so add_default's include_pattern call
(which is looking for the absolute cmd.egg_info) will match
them.


def reinitialize_command(self, command, reinit_subcommands=<NUM_LIT:0>):

cmd = self.distribution.reinitialize_command(<EOL>command, reinit_subcommands)<EOL>if command in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>cmd.install_lib = None<EOL><DEDENT>return cmd<EOL>

Supplement reinitialize_command to work around
http://bugs.python.org/issue20819


for c in '<STR_LIT:">', "<STR_LIT:'>", "<STR_LIT:\\>", "<STR_LIT:#>":<EOL><INDENT>if c in arg:<EOL><INDENT>return repr(arg)<EOL><DEDENT><DEDENT>if arg.split() != [arg]:<EOL><INDENT>return repr(arg)<EOL><DEDENT>return arg<EOL>

Quote an argument for later parsing by shlex.split()


if kind == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if kind == '<STR_LIT>':<EOL><INDENT>return os.path.join(<EOL>os.path.dirname(distutils.__file__), '<STR_LIT>'<EOL>)<EOL><DEDENT>if kind == '<STR_LIT:user>':<EOL><INDENT>dot = os.name == '<STR_LIT>' and '<STR_LIT:.>' or '<STR_LIT>'<EOL>return os.path.expanduser(convert_path("<STR_LIT>" % dot))<EOL><DEDENT>raise ValueError(<EOL>"<STR_LIT>", kind<EOL>)<EOL>

Get the filename of the distutils, local, global, or per-user config

    `kind` must be one of "local", "global", or "user"


def edit_config(filename, settings, dry_run=False):

from setuptools.compat import ConfigParser<EOL>log.debug("<STR_LIT>", filename)<EOL>opts = ConfigParser.RawConfigParser()<EOL>opts.read([filename])<EOL>for section, options in settings.items():<EOL><INDENT>if options is None:<EOL><INDENT>log.info("<STR_LIT>", section, filename)<EOL>opts.remove_section(section)<EOL><DEDENT>else:<EOL><INDENT>if not opts.has_section(section):<EOL><INDENT>log.debug("<STR_LIT>", section, filename)<EOL>opts.add_section(section)<EOL><DEDENT>for option, value in options.items():<EOL><INDENT>if value is None:<EOL><INDENT>log.debug(<EOL>"<STR_LIT>",<EOL>section, option, filename<EOL>)<EOL>opts.remove_option(section, option)<EOL>if not opts.options(section):<EOL><INDENT>log.info("<STR_LIT>",<EOL>section, filename)<EOL>opts.remove_section(section)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.debug(<EOL>"<STR_LIT>",<EOL>section, option, value, filename<EOL>)<EOL>opts.set(section, option, value)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>log.info("<STR_LIT>", filename)<EOL>if not dry_run:<EOL><INDENT>with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>opts.write(f)<EOL><DEDENT><DEDENT>

Edit a configuration file to include `settings`

    `settings` is a dictionary of dictionaries or ``None`` values, keyed by
    command/section name.  A ``None`` value means to delete the entire section,
    while a dictionary lists settings to be changed or deleted in that section.
    A setting of ``None`` means to delete that setting.


all_packages = (<EOL>pkg<EOL>for ns_pkg in self._get_SVEM_NSPs()<EOL>for pkg in self._all_packages(ns_pkg)<EOL>)<EOL>excl_specs = product(all_packages, self._gen_exclusion_paths())<EOL>return set(starmap(self._exclude_pkg_path, excl_specs))<EOL>

Return a collections.Sized collections.Container of paths to be
excluded for single_version_externally_managed installations.


def _exclude_pkg_path(self, pkg, exclusion_path):

parts = pkg.split('<STR_LIT:.>') + [exclusion_path]<EOL>return os.path.join(self.install_dir, *parts)<EOL>

Given a package name and exclusion path within that package,
compute the full exclusion path.


while pkg_name:<EOL><INDENT>yield pkg_name<EOL>pkg_name, sep, child = pkg_name.rpartition('<STR_LIT:.>')<EOL><DEDENT>

>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']


<EOL>if not self.distribution.namespace_packages:<EOL><INDENT>return []<EOL><DEDENT>install_cmd = self.get_finalized_command('<STR_LIT>')<EOL>svem = install_cmd.single_version_externally_managed<EOL>return self.distribution.namespace_packages if svem else []<EOL>

Get namespace packages (list) but only for
single_version_externally_managed installations and empty otherwise.


<EOL>yield '<STR_LIT>'<EOL>yield '<STR_LIT>'<EOL>yield '<STR_LIT>'<EOL>if not hasattr(imp, '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>base = os.path.join('<STR_LIT>', '<STR_LIT>' + imp.get_tag())<EOL>yield base + '<STR_LIT>'<EOL>yield base + '<STR_LIT>'<EOL>

Generate file paths to be excluded for namespace packages (bytecode
cache files).


all_files = []<EOL>for base, dirs, files in os.walk(dir, followlinks=True):<EOL><INDENT>if base==os.curdir or base.startswith(os.curdir+os.sep):<EOL><INDENT>base = base[<NUM_LIT:2>:]<EOL><DEDENT>if base:<EOL><INDENT>files = [os.path.join(base, f) for f in files]<EOL><DEDENT>all_files.extend(filter(os.path.isfile, files))<EOL><DEDENT>return all_files<EOL>

Find all files under 'dir' and return the list of full filenames
    (relative to 'dir').


@classmethod<EOL><INDENT>def find(cls, where='<STR_LIT:.>', exclude=(), include=('<STR_LIT:*>',)):<DEDENT>

out = cls._find_packages_iter(convert_path(where))<EOL>out = cls.require_parents(out)<EOL>includes = cls._build_filter(*include)<EOL>excludes = cls._build_filter('<STR_LIT>', '<STR_LIT>', *exclude)<EOL>out = filter(includes, out)<EOL>out = filterfalse(excludes, out)<EOL>return list(out)<EOL>

Return a list all Python packages found within directory 'where'

        'where' should be supplied as a "cross-platform" (i.e. URL-style)
        path; it will be converted to the appropriate local path syntax.
        'exclude' is a sequence of package names to exclude; '*' can be used
        as a wildcard in the names, such that 'foo.*' will exclude all
        subpackages of 'foo' (but not 'foo' itself).

        'include' is a sequence of package names to include.  If it's
        specified, only the named packages will be included.  If it's not
        specified, all found packages will be included.  'include' can contain
        shell style wildcard patterns just like 'exclude'.

        The list of included packages is built up first and then any
        explicitly excluded packages are removed from it.


found = []<EOL>for pkg in packages:<EOL><INDENT>base, sep, child = pkg.rpartition('<STR_LIT:.>')<EOL>if base and base not in found:<EOL><INDENT>continue<EOL><DEDENT>found.append(pkg)<EOL>yield pkg<EOL><DEDENT>

Exclude any apparent package that apparently doesn't include its
parent.

For example, exclude 'foo.bar' if 'foo' is not present.


for root, dirs, files in os.walk(base_path, followlinks=True):<EOL><INDENT>for dir in dirs:<EOL><INDENT>yield os.path.relpath(os.path.join(root, dir), base_path)<EOL><DEDENT><DEDENT>

Return all dirs in base_path, relative to base_path


return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)<EOL>

Given a list of patterns, return a callable that will be true only if
the input matches one of the patterns.


fs_enc = sys.getfilesystemencoding()<EOL>if isinstance(path, decoded_string):<EOL><INDENT>return path<EOL><DEDENT>for enc in (fs_enc, "<STR_LIT:utf-8>"):<EOL><INDENT>try:<EOL><INDENT>return path.decode(enc)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>

Ensure that the given path is decoded,
NONE when no expected encoding works


try:<EOL><INDENT>return string.encode(enc)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>return None<EOL><DEDENT>

turn unicode encoding into a functional routine


def _execfile(filename, globals, locals=None):

mode = '<STR_LIT:rb>'<EOL>if sys.version_info < (<NUM_LIT:2>, <NUM_LIT:7>):<EOL><INDENT>mode += '<STR_LIT>'<EOL><DEDENT>with open(filename, mode) as stream:<EOL><INDENT>script = stream.read()<EOL><DEDENT>if locals is None:<EOL><INDENT>locals = globals<EOL><DEDENT>code = compile(script, filename, '<STR_LIT>')<EOL>exec(code, globals, locals)<EOL>


if not os.path.isdir(replacement):<EOL><INDENT>os.makedirs(replacement)<EOL><DEDENT>saved = tempfile.tempdir<EOL>tempfile.tempdir = replacement<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>tempfile.tempdir = saved<EOL><DEDENT>

Monkey-patch tempfile.tempdir with replacement, ensuring it exists


saved = sys.modules.copy()<EOL>with ExceptionSaver() as saved_exc:<EOL><INDENT>yield saved<EOL><DEDENT>sys.modules.update(saved)<EOL>del_modules = (<EOL>mod_name for mod_name in sys.modules<EOL>if mod_name not in saved<EOL>and not mod_name.startswith('<STR_LIT>')<EOL>)<EOL>_clear_modules(del_modules)<EOL>saved_exc.resume()<EOL>

Context in which imported modules are saved.

Translates exceptions internal to the context into the equivalent exception
outside the context.


pattern = re.compile('<STR_LIT>')<EOL>return bool(pattern.match(mod_name))<EOL>

>>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True


modules = filter(_needs_hiding, sys.modules)<EOL>_clear_modules(modules)<EOL>

Remove references to setuptools' modules from sys.modules to allow the
invocation to import the most appropriate setuptools. This technique is
necessary to avoid issues such as #315 where setuptools upgrading itself
would fail to find a function declared in the metadata.


setup_dir = os.path.abspath(os.path.dirname(setup_script))<EOL>with setup_context(setup_dir):<EOL><INDENT>try:<EOL><INDENT>sys.argv[:] = [setup_script]+list(args)<EOL>sys.path.insert(<NUM_LIT:0>, setup_dir)<EOL>working_set.__init__()<EOL>working_set.callbacks.append(lambda dist:dist.activate())<EOL>def runner():<EOL><INDENT>ns = dict(__file__=setup_script, __name__='<STR_LIT:__main__>')<EOL>_execfile(setup_script, ns)<EOL><DEDENT>DirectorySandbox(setup_dir).run(runner)<EOL><DEDENT>except SystemExit as v:<EOL><INDENT>if v.args and v.args[<NUM_LIT:0>]:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>

Run a distutils setup script, sandboxed in its directory


@classmethod<EOL><INDENT>def dump(cls, type, exc):<DEDENT>

try:<EOL><INDENT>return pickle.dumps(type), pickle.dumps(exc)<EOL><DEDENT>except Exception:<EOL><INDENT>return cls.dump(cls, cls(repr(exc)))<EOL><DEDENT>

Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first.


if '<STR_LIT>' not in vars(self):<EOL><INDENT>return<EOL><DEDENT>type, exc = map(pickle.loads, self._saved)<EOL>compat.reraise(type, exc, self._tb)<EOL>


try:<EOL><INDENT>self._copy(self)<EOL>if _file:<EOL><INDENT>builtins.file = self._file<EOL><DEDENT>builtins.open = self._open<EOL>self._active = True<EOL>return func()<EOL><DEDENT>finally:<EOL><INDENT>self._active = False<EOL>if _file:<EOL><INDENT>builtins.file = _file<EOL><DEDENT>builtins.open = _open<EOL>self._copy(_os)<EOL><DEDENT>


return path<EOL>

Called to remap or validate any path, whether input or output


return self._validate_path(path)<EOL>


return (<EOL>self._remap_input(operation+'<STR_LIT>',src,*args,**kw),<EOL>self._remap_input(operation+'<STR_LIT>',dst,*args,**kw)<EOL>)<EOL>

Called for path pairs like rename, link, and symlink operations


def _remap_input(self, operation, path, *args, **kw):

if operation in self.write_ops and not self._ok(path):<EOL><INDENT>self._violation(operation, os.path.realpath(path), *args, **kw)<EOL><DEDENT>return path<EOL>


def _remap_pair(self, operation, src, dst, *args, **kw):

if not self._ok(src) or not self._ok(dst):<EOL><INDENT>self._violation(operation, src, dst, *args, **kw)<EOL><DEDENT>return (src,dst)<EOL>


def open(self, file, flags, mode=<NUM_LIT>, *args, **kw):

if flags & WRITE_FLAGS and not self._ok(file):<EOL><INDENT>self._violation("<STR_LIT>", file, flags, mode, *args, **kw)<EOL><DEDENT>return _os.open(file,flags,mode, *args, **kw)<EOL>


while cls.__module__.startswith('<STR_LIT>'):<EOL><INDENT>cls, = cls.__bases__<EOL><DEDENT>if not cls.__module__.startswith('<STR_LIT>'):<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>" % cls<EOL>)<EOL><DEDENT>return cls<EOL>

Protect against re-patching the distutils if reloaded

    Also ensures that no other distutils extension monkeypatched the distutils
    first.


environment_local = (<NUM_LIT:3>,) <= sys.version_info[:<NUM_LIT:3>] < (<NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:2>)<EOL>if not environment_local:<EOL><INDENT>return<EOL><DEDENT>def write_pkg_info(self, base_dir):<EOL><INDENT>"""<STR_LIT>"""<EOL>with open(os.path.join(base_dir, '<STR_LIT>'), '<STR_LIT:w>',<EOL>encoding='<STR_LIT>') as pkg_info:<EOL><INDENT>self.write_pkg_file(pkg_info)<EOL><DEDENT><DEDENT>distutils.dist.DistributionMetadata.write_pkg_info = write_pkg_info<EOL>

Workaround issue #197 - Python 3 prior to 3.2.2 uses an environment-local
encoding to save the pkg_info. Monkey-patch its write_pkg_info method to
correct this undesirable behavior.


def assert_string_list(dist, attr, value):

try:<EOL><INDENT>assert '<STR_LIT>'.join(value)!=value<EOL><DEDENT>except (TypeError,ValueError,AttributeError,AssertionError):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % (attr,value)<EOL>)<EOL><DEDENT>

Verify that value is a string list or None


assert_string_list(dist,attr,value)<EOL>for nsp in value:<EOL><INDENT>if not dist.has_contents_for(nsp):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" % nsp<EOL>)<EOL><DEDENT>if '<STR_LIT:.>' in nsp:<EOL><INDENT>parent = '<STR_LIT:.>'.join(nsp.split('<STR_LIT:.>')[:-<NUM_LIT:1>])<EOL>if parent not in value:<EOL><INDENT>distutils.log.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", nsp, parent<EOL>)<EOL><DEDENT><DEDENT><DEDENT>

Verify that namespace packages are valid


try:<EOL><INDENT>for k,v in value.items():<EOL><INDENT>if '<STR_LIT::>' in k:<EOL><INDENT>k,m = k.split('<STR_LIT::>',<NUM_LIT:1>)<EOL>if pkg_resources.invalid_marker(m):<EOL><INDENT>raise DistutilsSetupError("<STR_LIT>"+m)<EOL><DEDENT><DEDENT>list(pkg_resources.parse_requirements(v))<EOL><DEDENT><DEDENT>except (TypeError,ValueError,AttributeError):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>

Verify that extras_require mapping is valid


if bool(value) != value:<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>" % (attr,value)<EOL>)<EOL><DEDENT>

Verify that value is True, False, 0, or 1


def check_requirements(dist, attr, value):

try:<EOL><INDENT>list(pkg_resources.parse_requirements(value))<EOL><DEDENT>except (TypeError,ValueError):<EOL><INDENT>raise DistutilsSetupError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (attr,)<EOL>)<EOL><DEDENT>

Verify that install_requires is a valid requirements list


def check_entry_points(dist, attr, value):

try:<EOL><INDENT>pkg_resources.EntryPoint.parse_map(value)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise DistutilsSetupError(e)<EOL><DEDENT>

Verify that entry_points map is parseable


def check_package_data(dist, attr, value):

if isinstance(value,dict):<EOL><INDENT>for k,v in value.items():<EOL><INDENT>if not isinstance(k,str): break<EOL>try: iter(v)<EOL>except TypeError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>raise DistutilsSetupError(<EOL>attr+"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>

Verify that value is a dictionary of package names to glob lists


result = _Distribution.parse_command_line(self)<EOL>if self.features:<EOL><INDENT>self._finalize_features()<EOL><DEDENT>return result<EOL>

Process features after parsing command line options


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

Convert feature name to corresponding option attribute name


resolved_dists = pkg_resources.working_set.resolve(<EOL>pkg_resources.parse_requirements(requires),<EOL>installer=self.fetch_build_egg,<EOL>replace_conflicting=True,<EOL>)<EOL>for dist in resolved_dists:<EOL><INDENT>pkg_resources.working_set.add(dist, replace=True)<EOL><DEDENT>


try:<EOL><INDENT>cmd = self._egg_fetcher<EOL>cmd.package_index.to_scan = []<EOL><DEDENT>except AttributeError:<EOL><INDENT>from setuptools.command.easy_install import easy_install<EOL>dist = self.__class__({'<STR_LIT>':['<STR_LIT>']})<EOL>dist.parse_config_files()<EOL>opts = dist.get_option_dict('<STR_LIT>')<EOL>keep = (<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>)<EOL>for key in list(opts):<EOL><INDENT>if key not in keep:<EOL><INDENT>del opts[key]   <EOL><DEDENT><DEDENT>if self.dependency_links:<EOL><INDENT>links = self.dependency_links[:]<EOL>if '<STR_LIT>' in opts:<EOL><INDENT>links = opts['<STR_LIT>'][<NUM_LIT:1>].split() + links<EOL><DEDENT>opts['<STR_LIT>'] = ('<STR_LIT>', links)<EOL><DEDENT>install_dir = self.get_egg_cache_dir()<EOL>cmd = easy_install(<EOL>dist, args=["<STR_LIT:x>"], install_dir=install_dir, exclude_scripts=True,<EOL>always_copy=False, build_directory=None, editable=False,<EOL>upgrade=False, multi_version=True, no_report=True, user=False<EOL>)<EOL>cmd.ensure_finalized()<EOL>self._egg_fetcher = cmd<EOL><DEDENT>return cmd.easy_install(req)<EOL>


go = []<EOL>no = self.negative_opt.copy()<EOL>for name,feature in self.features.items():<EOL><INDENT>self._set_feature(name,None)<EOL>feature.validate(self)<EOL>if feature.optional:<EOL><INDENT>descr = feature.description<EOL>incdef = '<STR_LIT>'<EOL>excdef='<STR_LIT>'<EOL>if not feature.include_by_default():<EOL><INDENT>excdef, incdef = incdef, excdef<EOL><DEDENT>go.append(('<STR_LIT>'+name, None, '<STR_LIT>'+descr+incdef))<EOL>go.append(('<STR_LIT>'+name, None, '<STR_LIT>'+descr+excdef))<EOL>no['<STR_LIT>'+name] = '<STR_LIT>'+name<EOL><DEDENT><DEDENT>self.global_options = self.feature_options = go + self.global_options<EOL>self.negative_opt = self.feature_negopt = no<EOL>

Add --with-X/--without-X options based on optional features


<EOL>for name,feature in self.features.items():<EOL><INDENT>enabled = self.feature_is_included(name)<EOL>if enabled or (enabled is None and feature.include_by_default()):<EOL><INDENT>feature.include_in(self)<EOL>self._set_feature(name,<NUM_LIT:1>)<EOL><DEDENT><DEDENT>for name,feature in self.features.items():<EOL><INDENT>if not self.feature_is_included(name):<EOL><INDENT>feature.exclude_from(self)<EOL>self._set_feature(name,<NUM_LIT:0>)<EOL><DEDENT><DEDENT>

Add/remove features and resolve dependencies between them


if command in self.cmdclass:<EOL><INDENT>return self.cmdclass[command]<EOL><DEDENT>for ep in pkg_resources.iter_entry_points('<STR_LIT>',command):<EOL><INDENT>ep.require(installer=self.fetch_build_egg)<EOL>self.cmdclass[command] = cmdclass = ep.load()<EOL>return cmdclass<EOL><DEDENT>else:<EOL><INDENT>return _Distribution.get_command_class(self, command)<EOL><DEDENT>

Pluggable version of get_command_class()


setattr(self,self._feature_attrname(name),status)<EOL>


return getattr(self,self._feature_attrname(name))<EOL>

Return 1 if feature is included, 0 if excluded, 'None' if unknown


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 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 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 self.command_options.items():<EOL><INDENT>for opt,(src,val) in 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 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 PY2 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.


if have_pyrex():<EOL><INDENT>return<EOL><DEDENT>lang = self.language or '<STR_LIT>'<EOL>target_ext = '<STR_LIT>' if lang.lower() == '<STR_LIT>' else '<STR_LIT>'<EOL>sub = functools.partial(re.sub, '<STR_LIT>', target_ext)<EOL>self.sources = list(map(sub, self.sources))<EOL>

Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources.


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 * compat.long_type(<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'.


def extract_constant(code, symbol, default=-<NUM_LIT:1>):

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 not sys.platform.startswith('<STR_LIT>') and sys.platform != '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>incompatible = '<STR_LIT>', '<STR_LIT>'<EOL>for name in incompatible:<EOL><INDENT>del globals()[name]<EOL>__all__.remove(name)<EOL><DEDENT>

Patch the globals to remove the objects not available on some platforms.

XXX it'd be better to test assertions about bytecode instead.


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


__import__('<STR_LIT>')<EOL>SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW<EOL>SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD<EOL>SetFileAttributes.restype = ctypes.wintypes.BOOL<EOL>FILE_ATTRIBUTE_HIDDEN = <NUM_LIT><EOL>ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)<EOL>if not ret:<EOL><INDENT>raise ctypes.WinError()<EOL><DEDENT>

Set the hidden attribute on a file or directory.

From http://stackoverflow.com/questions/19622133/

`path` must be text.


return urllib2.build_opener(<EOL>VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())<EOL>).open<EOL>

Get a urlopen() replacement that uses ca_bundle for verification


if os.name=='<STR_LIT>':<EOL><INDENT>return get_win_certfile()<EOL><DEDENT>else:<EOL><INDENT>for cert_path in cert_paths:<EOL><INDENT>if os.path.isfile(cert_path):<EOL><INDENT>return cert_path<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>return pkg_resources.resource_filename('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>except (ImportError, ResolutionError, ExtractionError):<EOL><INDENT>return None<EOL><DEDENT>

Return an existing CA bundle path, or None


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 get_userpass_value(cli_value, config, key, prompt_strategy):

if cli_value is not None:<EOL><INDENT>return cli_value<EOL><DEDENT>elif config.get(key):<EOL><INDENT>return config[key]<EOL><DEDENT>else:<EOL><INDENT>return prompt_strategy()<EOL><DEDENT>

Gets the username / password from config.

    Uses the following rules:

    1. If it is specified on the cli (`cli_value`), use that.
    2. If `config[key]` is specified, use that.
    3. Otherwise prompt using `prompt_strategy`.

    :param cli_value: The value supplied from the command line or `None`.
    :type cli_value: unicode or `None`
    :param config: Config dictionary
    :type config: dict
    :param key: Key to find the config value.
    :type key: unicode
    :prompt_strategy: Argumentless function to return fallback value.
    :type prompt_strategy: function
    :returns: The value for the username / password
    :rtype: unicode


cps = os.environ.get("<STR_LIT>")<EOL>if cps:<EOL><INDENT>cov = coverage(config_file=cps, auto_data=True)<EOL>cov.start()<EOL>cov._warn_no_data = False<EOL>cov._warn_unimported_source = False<EOL><DEDENT>

Call this at Python startup to perhaps measure coverage.

    If the environment variable COVERAGE_PROCESS_START is defined, coverage
    measurement is started.  The value of the variable is the config file
    to use.

    There are two ways to configure your Python installation to invoke this
    function when Python starts:

    #. Create or append to sitecustomize.py to add these lines::

        import coverage
        coverage.process_startup()

    #. Create a .pth file in your Python installation containing::

        import coverage; coverage.process_startup()


def __init__(self, data_file=None, data_suffix=None, cover_pylib=None,<EOL>auto_data=False, timid=None, branch=None, config_file=True,<EOL>source=None, omit=None, include=None, debug=None,<EOL>debug_file=None):

from coverage import __version__<EOL>self._warnings = []<EOL>self.config = CoverageConfig()<EOL>if config_file:<EOL><INDENT>if config_file is True:<EOL><INDENT>config_file = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>self.config.from_file(config_file)<EOL><DEDENT>except ValueError:<EOL><INDENT>_, err, _ = sys.exc_info()<EOL>raise CoverageException(<EOL>"<STR_LIT>" % (config_file, err)<EOL>)<EOL><DEDENT><DEDENT>self.config.from_environment('<STR_LIT>')<EOL>env_data_file = os.environ.get('<STR_LIT>')<EOL>if env_data_file:<EOL><INDENT>self.config.data_file = env_data_file<EOL><DEDENT>self.config.from_args(<EOL>data_file=data_file, cover_pylib=cover_pylib, timid=timid,<EOL>branch=branch, parallel=bool_or_none(data_suffix),<EOL>source=source, omit=omit, include=include, debug=debug,<EOL>)<EOL>self.debug = DebugControl(self.config.debug, debug_file or sys.stderr)<EOL>self.auto_data = auto_data<EOL>self._exclude_re = {}<EOL>self._exclude_regex_stale()<EOL>self.file_locator = FileLocator()<EOL>self.source = []<EOL>self.source_pkgs = []<EOL>for src in self.config.source or []:<EOL><INDENT>if os.path.exists(src):<EOL><INDENT>self.source.append(self.file_locator.canonical_filename(src))<EOL><DEDENT>else:<EOL><INDENT>self.source_pkgs.append(src)<EOL><DEDENT><DEDENT>self.omit = prep_patterns(self.config.omit)<EOL>self.include = prep_patterns(self.config.include)<EOL>self.collector = Collector(<EOL>self._should_trace, timid=self.config.timid,<EOL>branch=self.config.branch, warn=self._warn<EOL>)<EOL>if data_suffix or self.config.parallel:<EOL><INDENT>if not isinstance(data_suffix, string_class):<EOL><INDENT>data_suffix = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data_suffix = None<EOL><DEDENT>self.data_suffix = None<EOL>self.run_suffix = data_suffix<EOL>self.data = CoverageData(<EOL>basename=self.config.data_file,<EOL>collector="<STR_LIT>" % __version__,<EOL>debug=self.debug,<EOL>)<EOL>self.pylib_dirs = []<EOL>if not self.config.cover_pylib:<EOL><INDENT>for m in (atexit, os, random, socket, _structseq):<EOL><INDENT>if m is not None and hasattr(m, "<STR_LIT>"):<EOL><INDENT>m_dir = self._canonical_dir(m)<EOL>if m_dir not in self.pylib_dirs:<EOL><INDENT>self.pylib_dirs.append(m_dir)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.cover_dir = self._canonical_dir(__file__)<EOL>self.source_match = None<EOL>self.pylib_match = self.cover_match = None<EOL>self.include_match = self.omit_match = None<EOL>Numbers.set_precision(self.config.precision)<EOL>self._warn_no_data = True<EOL>self._warn_unimported_source = True<EOL>self._started = False<EOL>self._measured = False<EOL>atexit.register(self._atexit)<EOL>

`data_file` is the base name of the data file to use, defaulting to
".coverage".  `data_suffix` is appended (with a dot) to `data_file` to
create the final file name.  If `data_suffix` is simply True, then a
suffix is created with the machine and process identity included.

`cover_pylib` is a boolean determining whether Python code installed
with the Python interpreter is measured.  This includes the Python
standard library and any packages installed with the interpreter.

If `auto_data` is true, then any existing data file will be read when
coverage measurement starts, and data will be saved automatically when
measurement stops.

If `timid` is true, then a slower and simpler trace function will be
used.  This is important for some environments where manipulation of
tracing functions breaks the faster trace function.

If `branch` is true, then branch coverage will be measured in addition
to the usual statement coverage.

`config_file` determines what config file to read.  If it is a string,
it is the name of the config file to read.  If it is True, then a
standard file is read (".coveragerc").  If it is False, then no file is
read.

`source` is a list of file paths or package names.  Only code located
in the trees indicated by the file paths or package names will be
measured.

`include` and `omit` are lists of filename patterns. Files that match
`include` will be measured, files that match `omit` will not.  Each
will also accept a single string argument.

`debug` is a list of strings indicating what debugging information is
desired. `debug_file` is the file to write debug messages to,
defaulting to stderr.


return os.path.split(CodeUnit(morf, self.file_locator).filename)[<NUM_LIT:0>]<EOL>

Return the canonical directory of the module or file `morf`.


if not filename.endswith("<STR_LIT>"):<EOL><INDENT>if filename[-<NUM_LIT:4>:-<NUM_LIT:1>] == "<STR_LIT>":<EOL><INDENT>filename = filename[:-<NUM_LIT:1>]<EOL><DEDENT>elif filename.endswith("<STR_LIT>"): <EOL><INDENT>filename = filename[:-<NUM_LIT:9>] + "<STR_LIT>"<EOL><DEDENT><DEDENT>return filename<EOL>


def _should_trace_with_reason(self, filename, frame):

if not filename:<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT>if filename.startswith('<STR_LIT:<>'):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT>self._check_for_packages()<EOL>dunder_file = frame.f_globals.get('<STR_LIT>')<EOL>if dunder_file:<EOL><INDENT>filename = self._source_for_file(dunder_file)<EOL><DEDENT>if filename.endswith("<STR_LIT>"):<EOL><INDENT>filename = filename[:-<NUM_LIT:9>] + "<STR_LIT>"<EOL><DEDENT>canonical = self.file_locator.canonical_filename(filename)<EOL>if self.source_match:<EOL><INDENT>if not self.source_match.match(canonical):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT><DEDENT>elif self.include_match:<EOL><INDENT>if not self.include_match.match(canonical):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.pylib_match and self.pylib_match.match(canonical):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT>if self.cover_match and self.cover_match.match(canonical):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT><DEDENT>if self.omit_match and self.omit_match.match(canonical):<EOL><INDENT>return None, "<STR_LIT>"<EOL><DEDENT>return canonical, "<STR_LIT>"<EOL>

Decide whether to trace execution in `filename`, with a reason.

        This function is called from the trace function.  As each new file name
        is encountered, this function determines whether it is traced or not.

        Returns a pair of values:  the first indicates whether the file should
        be traced: it's a canonicalized filename if it should be traced, None
        if it should not.  The second value is a string, the resason for the
        decision.


def _should_trace(self, filename, frame):

canonical, reason = self._should_trace_with_reason(filename, frame)<EOL>if self.debug.should('<STR_LIT>'):<EOL><INDENT>if not canonical:<EOL><INDENT>msg = "<STR_LIT>" % (filename, reason)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % (filename,)<EOL><DEDENT>self.debug.write(msg)<EOL><DEDENT>return canonical<EOL>

Decide whether to trace execution in `filename`.

        Calls `_should_trace_with_reason`, and returns just the decision.


self._warnings.append(msg)<EOL>sys.stderr.write("<STR_LIT>" % msg)<EOL>


<EOL>if self.source_pkgs:<EOL><INDENT>found = []<EOL>for pkg in self.source_pkgs:<EOL><INDENT>try:<EOL><INDENT>mod = sys.modules[pkg]<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>found.append(pkg)<EOL>try:<EOL><INDENT>pkg_file = mod.__file__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pkg_file = None<EOL><DEDENT>else:<EOL><INDENT>d, f = os.path.split(pkg_file)<EOL>if f.startswith('<STR_LIT>'):<EOL><INDENT>pkg_file = d<EOL><DEDENT>else:<EOL><INDENT>pkg_file = self._source_for_file(pkg_file)<EOL><DEDENT>pkg_file = self.file_locator.canonical_filename(pkg_file)<EOL>if not os.path.exists(pkg_file):<EOL><INDENT>pkg_file = None<EOL><DEDENT><DEDENT>if pkg_file:<EOL><INDENT>self.source.append(pkg_file)<EOL>self.source_match.add(pkg_file)<EOL><DEDENT>else:<EOL><INDENT>self._warn("<STR_LIT>" % pkg)<EOL><DEDENT><DEDENT>for pkg in found:<EOL><INDENT>self.source_pkgs.remove(pkg)<EOL><DEDENT><DEDENT>

Update the source_match matcher with latest imported packages.


self.data.usefile(usecache)<EOL>

Control the use of a data file (incorrectly called a cache).

        `usecache` is true or false, whether to read and write data on disk.


self.collector.reset()<EOL>self.data.read()<EOL>

Load previously-collected coverage data from the data file.


if self.run_suffix:<EOL><INDENT>self.data_suffix = self.run_suffix<EOL><DEDENT>if self.auto_data:<EOL><INDENT>self.load()<EOL><DEDENT>if self.source or self.source_pkgs:<EOL><INDENT>self.source_match = TreeMatcher(self.source)<EOL><DEDENT>else:<EOL><INDENT>if self.cover_dir:<EOL><INDENT>self.cover_match = TreeMatcher([self.cover_dir])<EOL><DEDENT>if self.pylib_dirs:<EOL><INDENT>self.pylib_match = TreeMatcher(self.pylib_dirs)<EOL><DEDENT><DEDENT>if self.include:<EOL><INDENT>self.include_match = FnmatchMatcher(self.include)<EOL><DEDENT>if self.omit:<EOL><INDENT>self.omit_match = FnmatchMatcher(self.omit)<EOL><DEDENT>if self.debug.should('<STR_LIT>'):<EOL><INDENT>self.debug.write("<STR_LIT>")<EOL>config_info = sorted(self.config.__dict__.items())<EOL>self.debug.write_formatted_info(config_info)<EOL><DEDENT>if self.debug.should('<STR_LIT>'):<EOL><INDENT>self.debug.write("<STR_LIT>")<EOL>self.debug.write_formatted_info(self.sysinfo())<EOL><DEDENT>self.collector.start()<EOL>self._started = True<EOL>self._measured = True<EOL>

Start measuring code coverage.

        Coverage measurement actually occurs in functions called after `start`
        is invoked.  Statements in the same scope as `start` won't be measured.

        Once you invoke `start`, you must also call `stop` eventually, or your
        process might not shut down cleanly.


self._started = False<EOL>self.collector.stop()<EOL>


if self._started:<EOL><INDENT>self.stop()<EOL><DEDENT>if self.auto_data:<EOL><INDENT>self.save()<EOL><DEDENT>


self.collector.reset()<EOL>self.data.erase()<EOL>

Erase previously-collected coverage data.

        This removes the in-memory data collected in this session as well as
        discarding the data file.


setattr(self.config, which + "<STR_LIT>", [])<EOL>self._exclude_regex_stale()<EOL>


def exclude(self, regex, which='<STR_LIT>'):

excl_list = getattr(self.config, which + "<STR_LIT>")<EOL>excl_list.append(regex)<EOL>self._exclude_regex_stale()<EOL>

Exclude source lines from execution consideration.

        A number of lists of regular expressions are maintained.  Each list
        selects lines that are treated differently during reporting.

        `which` determines which list is modified.  The "exclude" list selects
        lines that are not considered executable at all.  The "partial" list
        indicates lines with branches that are not taken.

        `regex` is a regular expression.  The regex is added to the specified
        list.  If any of the regexes in the list is found in a line, the line
        is marked for special treatment during reporting.


Drop all the compiled exclusion regexes, a list was modified.


if which not in self._exclude_re:<EOL><INDENT>excl_list = getattr(self.config, which + "<STR_LIT>")<EOL>self._exclude_re[which] = join_regex(excl_list)<EOL><DEDENT>return self._exclude_re[which]<EOL>

Return a compiled regex for the given exclusion list.


return getattr(self.config, which + "<STR_LIT>")<EOL>

Return a list of excluded regex patterns.

        `which` indicates which list is desired.  See `exclude` for the lists
        that are available, and their meaning.


data_suffix = self.data_suffix<EOL>if data_suffix is True:<EOL><INDENT>extra = "<STR_LIT>"<EOL>if _TEST_NAME_FILE:<EOL><INDENT>f = open(_TEST_NAME_FILE)<EOL>test_name = f.read()<EOL>f.close()<EOL>extra = "<STR_LIT:.>" + test_name<EOL><DEDENT>data_suffix = "<STR_LIT>" % (<EOL>socket.gethostname(), extra, os.getpid(),<EOL>random.randint(<NUM_LIT:0>, <NUM_LIT>)<EOL>)<EOL><DEDENT>self._harvest_data()<EOL>self.data.write(suffix=data_suffix)<EOL>

Save the collected coverage data to the data file.


aliases = None<EOL>if self.config.paths:<EOL><INDENT>aliases = PathAliases(self.file_locator)<EOL>for paths in self.config.paths.values():<EOL><INDENT>result = paths[<NUM_LIT:0>]<EOL>for pattern in paths[<NUM_LIT:1>:]:<EOL><INDENT>aliases.add(pattern, result)<EOL><DEDENT><DEDENT><DEDENT>self.data.combine_parallel_data(aliases=aliases)<EOL>

Combine together a number of similarly-named coverage data files.

        All coverage data files whose name starts with `data_file` (from the
        coverage() constructor) will be read, and combined together into the
        current measurements.


if not self._measured:<EOL><INDENT>return<EOL><DEDENT>self.data.add_line_data(self.collector.get_line_data())<EOL>self.data.add_arc_data(self.collector.get_arc_data())<EOL>self.collector.reset()<EOL>if self._warn_unimported_source:<EOL><INDENT>for pkg in self.source_pkgs:<EOL><INDENT>self._warn("<STR_LIT>" % pkg)<EOL><DEDENT><DEDENT>summary = self.data.summary()<EOL>if not summary and self._warn_no_data:<EOL><INDENT>self._warn("<STR_LIT>")<EOL><DEDENT>for src in self.source:<EOL><INDENT>for py_file in find_python_files(src):<EOL><INDENT>py_file = self.file_locator.canonical_filename(py_file)<EOL>if self.omit_match and self.omit_match.match(py_file):<EOL><INDENT>continue<EOL><DEDENT>self.data.touch_file(py_file)<EOL><DEDENT><DEDENT>self._measured = False<EOL>

Get the collected data and reset the collector.

        Also warn about various problems collecting data.


f, s, _, m, mf = self.analysis2(morf)<EOL>return f, s, m, mf<EOL>

Like `analysis2` but doesn't return excluded line numbers.


Analyze a module.

        `morf` is a module or a filename.  It will be analyzed to determine
        its coverage statistics.  The return value is a 5-tuple:

        * The filename for the module.
        * A list of line numbers of executable statements.
        * A list of line numbers of excluded statements.
        * A list of line numbers of statements not run (missing from
          execution).
        * A readable formatted string of the missing line numbers.

        The analysis uses the source file itself and the current measured
        coverage data.


self._harvest_data()<EOL>if not isinstance(it, CodeUnit):<EOL><INDENT>it = code_unit_factory(it, self.file_locator)[<NUM_LIT:0>]<EOL><DEDENT>return Analysis(self, it)<EOL>

Analyze a single morf or code unit.

        Returns an `Analysis` object.


def report(self, morfs=None, show_missing=True, ignore_errors=None,<EOL>file=None,                          <EOL>omit=None, include=None<EOL>):

self._harvest_data()<EOL>self.config.from_args(<EOL>ignore_errors=ignore_errors, omit=omit, include=include,<EOL>show_missing=show_missing,<EOL>)<EOL>reporter = SummaryReporter(self, self.config)<EOL>return reporter.report(morfs, outfile=file)<EOL>

Write a summary report to `file`.

        Each module in `morfs` is listed, with counts of statements, executed
        statements, missing statements, and a list of lines missed.

        `include` is a list of filename patterns.  Modules whose filenames
        match those patterns will be included in the report. Modules matching
        `omit` will not be included in the report.

        Returns a float, the total percentage covered.


def annotate(self, morfs=None, directory=None, ignore_errors=None,<EOL>omit=None, include=None):

self._harvest_data()<EOL>self.config.from_args(<EOL>ignore_errors=ignore_errors, omit=omit, include=include<EOL>)<EOL>reporter = AnnotateReporter(self, self.config)<EOL>reporter.report(morfs, directory=directory)<EOL>

Annotate a list of modules.

        Each module in `morfs` is annotated.  The source is written to a new
        file, named with a ",cover" suffix, with each line prefixed with a
        marker to indicate the coverage of the line.  Covered lines have ">",
        excluded lines have "-", and missing lines have "!".

        See `coverage.report()` for other arguments.


def html_report(self, morfs=None, directory=None, ignore_errors=None,<EOL>omit=None, include=None, extra_css=None, title=None):

self._harvest_data()<EOL>self.config.from_args(<EOL>ignore_errors=ignore_errors, omit=omit, include=include,<EOL>html_dir=directory, extra_css=extra_css, html_title=title,<EOL>)<EOL>reporter = HtmlReporter(self, self.config)<EOL>return reporter.report(morfs)<EOL>

Generate an HTML report.

        The HTML is written to `directory`.  The file "index.html" is the
        overview starting point, with links to more detailed pages for
        individual modules.

        `extra_css` is a path to a file of other CSS to apply on the page.
        It will be copied into the HTML directory.

        `title` is a text string (not HTML) to use as the title of the HTML
        report.

        See `coverage.report()` for other arguments.

        Returns a float, the total percentage covered.


def xml_report(self, morfs=None, outfile=None, ignore_errors=None,<EOL>omit=None, include=None):

self._harvest_data()<EOL>self.config.from_args(<EOL>ignore_errors=ignore_errors, omit=omit, include=include,<EOL>xml_output=outfile,<EOL>)<EOL>file_to_close = None<EOL>delete_file = False<EOL>if self.config.xml_output:<EOL><INDENT>if self.config.xml_output == '<STR_LIT:->':<EOL><INDENT>outfile = sys.stdout<EOL><DEDENT>else:<EOL><INDENT>outfile = open(self.config.xml_output, "<STR_LIT:w>")<EOL>file_to_close = outfile<EOL><DEDENT><DEDENT>try:<EOL><INDENT>try:<EOL><INDENT>reporter = XmlReporter(self, self.config)<EOL>return reporter.report(morfs, outfile=outfile)<EOL><DEDENT>except CoverageException:<EOL><INDENT>delete_file = True<EOL>raise<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if file_to_close:<EOL><INDENT>file_to_close.close()<EOL>if delete_file:<EOL><INDENT>file_be_gone(self.config.xml_output)<EOL><DEDENT><DEDENT><DEDENT>

Generate an XML report of coverage results.

        The report is compatible with Cobertura reports.

        Each module in `morfs` is included in the report.  `outfile` is the
        path to write the file to, "-" will write to stdout.

        See `coverage.report()` for other arguments.

        Returns a float, the total percentage covered.


import coverage as covmod<EOL>import platform, re<EOL>try:<EOL><INDENT>implementation = platform.python_implementation()<EOL><DEDENT>except AttributeError:<EOL><INDENT>implementation = "<STR_LIT>"<EOL><DEDENT>info = [<EOL>('<STR_LIT:version>', covmod.__version__),<EOL>('<STR_LIT>', covmod.__file__),<EOL>('<STR_LIT>', self.cover_dir),<EOL>('<STR_LIT>', self.pylib_dirs),<EOL>('<STR_LIT>', self.collector.tracer_name()),<EOL>('<STR_LIT>', self.config.attempted_config_files),<EOL>('<STR_LIT>', self.config.config_files),<EOL>('<STR_LIT>', self.data.filename),<EOL>('<STR_LIT>', sys.version.replace('<STR_LIT:\n>', '<STR_LIT>')),<EOL>('<STR_LIT>', platform.platform()),<EOL>('<STR_LIT>', implementation),<EOL>('<STR_LIT>', sys.executable),<EOL>('<STR_LIT>', os.getcwd()),<EOL>('<STR_LIT:path>', sys.path),<EOL>('<STR_LIT>', sorted([<EOL>("<STR_LIT>" % (k, v)) for k, v in iitems(os.environ)<EOL>if re.search(r"<STR_LIT>", k)<EOL>])),<EOL>('<STR_LIT>', "<STR_LIT:U+0020>".join(getattr(sys, '<STR_LIT>', ['<STR_LIT>']))),<EOL>]<EOL>if self.source_match:<EOL><INDENT>info.append(('<STR_LIT>', self.source_match.info()))<EOL><DEDENT>if self.include_match:<EOL><INDENT>info.append(('<STR_LIT>', self.include_match.info()))<EOL><DEDENT>if self.omit_match:<EOL><INDENT>info.append(('<STR_LIT>', self.omit_match.info()))<EOL><DEDENT>if self.cover_match:<EOL><INDENT>info.append(('<STR_LIT>', self.cover_match.info()))<EOL><DEDENT>if self.pylib_match:<EOL><INDENT>info.append(('<STR_LIT>', self.pylib_match.info()))<EOL><DEDENT>return info<EOL>

Return a list of (key, value) pairs showing internal information.


self.code.append("<STR_LIT:U+0020>" * self.indent_amount)<EOL>self.code.append(line)<EOL>self.code.append("<STR_LIT:\n>")<EOL>

Add a line of source to the code.

        Don't include indentations or newlines.


sect = CodeBuilder(self.indent_amount)<EOL>self.code.append(sect)<EOL>return sect<EOL>


self.indent_amount += <NUM_LIT:4><EOL>

Increase the current indent for following lines.


self.indent_amount -= <NUM_LIT:4><EOL>

Decrease the current indent for following lines.


assert self.indent_amount == <NUM_LIT:0><EOL>g = {}<EOL>code_text = str(self)<EOL>exec(code_text, g)<EOL>return g[fn_name]<EOL>

Compile the code, and return the function `fn_name`.


self.text = text<EOL>self.context = {}<EOL>for context in contexts:<EOL><INDENT>self.context.update(context)<EOL><DEDENT>code = CodeBuilder()<EOL>code.add_line("<STR_LIT>")<EOL>code.indent()<EOL>vars_code = code.add_section()<EOL>self.all_vars = set()<EOL>self.loop_vars = set()<EOL>code.add_line("<STR_LIT>")<EOL>code.add_line("<STR_LIT>")<EOL>code.add_line("<STR_LIT>")<EOL>code.add_line("<STR_LIT>")<EOL>buffered = []<EOL>def flush_output():<EOL><INDENT>"""<STR_LIT>"""<EOL>if len(buffered) == <NUM_LIT:1>:<EOL><INDENT>code.add_line("<STR_LIT>" % buffered[<NUM_LIT:0>])<EOL><DEDENT>elif len(buffered) > <NUM_LIT:1>:<EOL><INDENT>code.add_line("<STR_LIT>" % "<STR_LIT:U+002C>".join(buffered))<EOL><DEDENT>del buffered[:]<EOL><DEDENT>toks = re.split(r"<STR_LIT>", text)<EOL>ops_stack = []<EOL>for tok in toks:<EOL><INDENT>if tok.startswith('<STR_LIT>'):<EOL><INDENT>buffered.append("<STR_LIT>" % self.expr_code(tok[<NUM_LIT:2>:-<NUM_LIT:2>].strip()))<EOL><DEDENT>elif tok.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>elif tok.startswith('<STR_LIT>'):<EOL><INDENT>flush_output()<EOL>words = tok[<NUM_LIT:2>:-<NUM_LIT:2>].strip().split()<EOL>if words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>assert len(words) == <NUM_LIT:2><EOL>ops_stack.append('<STR_LIT>')<EOL>code.add_line("<STR_LIT>" % self.expr_code(words[<NUM_LIT:1>]))<EOL>code.indent()<EOL><DEDENT>elif words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>assert len(words) == <NUM_LIT:4> and words[<NUM_LIT:2>] == '<STR_LIT>'<EOL>ops_stack.append('<STR_LIT>')<EOL>self.loop_vars.add(words[<NUM_LIT:1>])<EOL>code.add_line(<EOL>"<STR_LIT>" % (<EOL>words[<NUM_LIT:1>],<EOL>self.expr_code(words[<NUM_LIT:3>])<EOL>)<EOL>)<EOL>code.indent()<EOL><DEDENT>elif words[<NUM_LIT:0>].startswith('<STR_LIT:end>'):<EOL><INDENT>end_what = words[<NUM_LIT:0>][<NUM_LIT:3>:]<EOL>if ops_stack[-<NUM_LIT:1>] != end_what:<EOL><INDENT>raise SyntaxError("<STR_LIT>" % end_what)<EOL><DEDENT>ops_stack.pop()<EOL>code.dedent()<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxError("<STR_LIT>" % words[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if tok:<EOL><INDENT>buffered.append("<STR_LIT>" % tok)<EOL><DEDENT><DEDENT><DEDENT>flush_output()<EOL>for var_name in self.all_vars - self.loop_vars:<EOL><INDENT>vars_code.add_line("<STR_LIT>" % (var_name, var_name))<EOL><DEDENT>if ops_stack:<EOL><INDENT>raise SyntaxError("<STR_LIT>" % ops_stack[-<NUM_LIT:1>])<EOL><DEDENT>code.add_line("<STR_LIT>")<EOL>code.dedent()<EOL>self.render_function = code.get_function('<STR_LIT>')<EOL>

Construct a Templite with the given `text`.

        `contexts` are dictionaries of values to use for future renderings.
        These are good for filters and global values.


if "<STR_LIT:|>" in expr:<EOL><INDENT>pipes = expr.split("<STR_LIT:|>")<EOL>code = self.expr_code(pipes[<NUM_LIT:0>])<EOL>for func in pipes[<NUM_LIT:1>:]:<EOL><INDENT>self.all_vars.add(func)<EOL>code = "<STR_LIT>" % (func, code)<EOL><DEDENT><DEDENT>elif "<STR_LIT:.>" in expr:<EOL><INDENT>dots = expr.split("<STR_LIT:.>")<EOL>code = self.expr_code(dots[<NUM_LIT:0>])<EOL>args = [repr(d) for d in dots[<NUM_LIT:1>:]]<EOL>code = "<STR_LIT>" % (code, "<STR_LIT:U+002CU+0020>".join(args))<EOL><DEDENT>else:<EOL><INDENT>self.all_vars.add(expr)<EOL>code = "<STR_LIT>" % expr<EOL><DEDENT>return code<EOL>

Generate a Python expression for `expr`.


<EOL>ctx = dict(self.context)<EOL>if context:<EOL><INDENT>ctx.update(context)<EOL><DEDENT>return self.render_function(ctx, self.do_dots)<EOL>

Render this template by applying it to `context`.

        `context` is a dictionary of values to use in this rendering.


for dot in dots:<EOL><INDENT>try:<EOL><INDENT>value = getattr(value, dot)<EOL><DEDENT>except AttributeError:<EOL><INDENT>value = value[dot]<EOL><DEDENT>if hasattr(value, '<STR_LIT>'):<EOL><INDENT>value = value()<EOL><DEDENT><DEDENT>return value<EOL>


kwargs = {}<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:2>):<EOL><INDENT>kwargs['<STR_LIT>'] = "<STR_LIT:utf-8>"<EOL><DEDENT>return configparser.RawConfigParser.read(self, filename, **kwargs)<EOL>

Read a filename as UTF-8 configuration data.


value_list = self.get(section, option)<EOL>values = []<EOL>for value_line in value_list.split('<STR_LIT:\n>'):<EOL><INDENT>for value in value_line.split('<STR_LIT:U+002C>'):<EOL><INDENT>value = value.strip()<EOL>if value:<EOL><INDENT>values.append(value)<EOL><DEDENT><DEDENT><DEDENT>return values<EOL>

Read a list of strings.

        The value of `section` and `option` is treated as a comma- and newline-
        separated list of strings.  Each value is stripped of whitespace.

        Returns the list of strings.


value_list = self.get(section, option)<EOL>return list(filter(None, value_list.split('<STR_LIT:\n>')))<EOL>

Read a list of full-line strings.

        The value of `section` and `option` is treated as a newline-separated
        list of strings.  Each value is stripped of whitespace.

        Returns the list of strings.


<EOL>self.attempted_config_files = []<EOL>self.config_files = []<EOL>self.branch = False<EOL>self.cover_pylib = False<EOL>self.data_file = "<STR_LIT>"<EOL>self.parallel = False<EOL>self.timid = False<EOL>self.source = None<EOL>self.debug = []<EOL>self.exclude_list = DEFAULT_EXCLUDE[:]<EOL>self.ignore_errors = False<EOL>self.include = None<EOL>self.omit = None<EOL>self.partial_list = DEFAULT_PARTIAL[:]<EOL>self.partial_always_list = DEFAULT_PARTIAL_ALWAYS[:]<EOL>self.precision = <NUM_LIT:0><EOL>self.show_missing = False<EOL>self.html_dir = "<STR_LIT>"<EOL>self.extra_css = None<EOL>self.html_title = "<STR_LIT>"<EOL>self.xml_output = "<STR_LIT>"<EOL>self.paths = {}<EOL>

Initialize the configuration attributes to their defaults.


<EOL>env = os.environ.get(env_var, '<STR_LIT>')<EOL>if env:<EOL><INDENT>self.timid = ('<STR_LIT>' in env)<EOL><DEDENT>

Read configuration from the `env_var` environment variable.


for k, v in iitems(kwargs):<EOL><INDENT>if v is not None:<EOL><INDENT>if k in self.MUST_BE_LIST and isinstance(v, string_class):<EOL><INDENT>v = [v]<EOL><DEDENT>setattr(self, k, v)<EOL><DEDENT><DEDENT>


self.attempted_config_files.append(filename)<EOL>cp = HandyConfigParser()<EOL>files_read = cp.read(filename)<EOL>if files_read is not None:  <EOL><INDENT>self.config_files.extend(files_read)<EOL><DEDENT>for option_spec in self.CONFIG_FILE_OPTIONS:<EOL><INDENT>self.set_attr_from_config_option(cp, *option_spec)<EOL><DEDENT>if cp.has_section('<STR_LIT>'):<EOL><INDENT>for option in cp.options('<STR_LIT>'):<EOL><INDENT>self.paths[option] = cp.getlist('<STR_LIT>', option)<EOL><DEDENT><DEDENT>

Read configuration from a .rc file.

        `filename` is a file name to read.


def set_attr_from_config_option(self, cp, attr, where, type_='<STR_LIT>'):

section, option = where.split("<STR_LIT::>")<EOL>if cp.has_option(section, option):<EOL><INDENT>method = getattr(cp, '<STR_LIT>'+type_)<EOL>setattr(self, attr, method(section, option))<EOL><DEDENT>

Set an attribute on self if it exists in the ConfigParser.


start, end = pair<EOL>if start == end:<EOL><INDENT>return "<STR_LIT>" % start<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % (start, end)<EOL><DEDENT>

Make a nice string representation of a pair of numbers.

    If the numbers are equal, just return the number, otherwise return the pair
    with a dash between them, indicating the range.


pairs = []<EOL>i = <NUM_LIT:0><EOL>j = <NUM_LIT:0><EOL>start = None<EOL>statements = sorted(statements)<EOL>lines = sorted(lines)<EOL>while i < len(statements) and j < len(lines):<EOL><INDENT>if statements[i] == lines[j]:<EOL><INDENT>if start == None:<EOL><INDENT>start = lines[j]<EOL><DEDENT>end = lines[j]<EOL>j += <NUM_LIT:1><EOL><DEDENT>elif start:<EOL><INDENT>pairs.append((start, end))<EOL>start = None<EOL><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>if start:<EOL><INDENT>pairs.append((start, end))<EOL><DEDENT>ret = '<STR_LIT:U+002CU+0020>'.join(map(nice_pair, pairs))<EOL>return ret<EOL>

Nicely format a list of line numbers.

    Format a list of line numbers for printing by coalescing groups of lines as
    long as the lines represent consecutive statements.  This will coalesce
    even if there are gaps between statements.

    For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
    `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".


stack = inspect.stack()[:<NUM_LIT:0>:-<NUM_LIT:1>]<EOL>return "<STR_LIT:\n>".join(["<STR_LIT>" % (t[<NUM_LIT:3>],t[<NUM_LIT:1>],t[<NUM_LIT:2>]) for t in stack])<EOL>

Return a string summarizing the call stack.


attr = "<STR_LIT>" + fn.__name__<EOL>def _wrapped(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not hasattr(self, attr):<EOL><INDENT>setattr(self, attr, fn(self))<EOL><DEDENT>return getattr(self, attr)<EOL><DEDENT>return _wrapped<EOL>

A decorator to cache the result of an expensive operation.

    Only applies to methods with no arguments.


if b is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return bool(b)<EOL><DEDENT>


if len(regexes) > <NUM_LIT:1>:<EOL><INDENT>return "<STR_LIT:|>".join(["<STR_LIT>" % r for r in regexes])<EOL><DEDENT>elif regexes:<EOL><INDENT>return regexes[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>

Combine a list of regexes into one that matches any of them.


try:<EOL><INDENT>os.remove(path)<EOL><DEDENT>except OSError:<EOL><INDENT>_, e, _ = sys.exc_info()<EOL>if e.errno != errno.ENOENT:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>

Remove a file, and don't get annoyed if it doesn't exist.


self.md5.update(to_bytes(str(type(v))))<EOL>if isinstance(v, string_class):<EOL><INDENT>self.md5.update(to_bytes(v))<EOL><DEDENT>elif v is None:<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(v, (int, float)):<EOL><INDENT>self.md5.update(to_bytes(str(v)))<EOL><DEDENT>elif isinstance(v, (tuple, list)):<EOL><INDENT>for e in v:<EOL><INDENT>self.update(e)<EOL><DEDENT><DEDENT>elif isinstance(v, dict):<EOL><INDENT>keys = v.keys()<EOL>for k in sorted(keys):<EOL><INDENT>self.update(k)<EOL>self.update(v[k])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for k in dir(v):<EOL><INDENT>if k.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>a = getattr(v, k)<EOL>if inspect.isroutine(a):<EOL><INDENT>continue<EOL><DEDENT>self.update(k)<EOL>self.update(a)<EOL><DEDENT><DEDENT>

Add `v` to the hash, recursively if needed.


return self.md5.digest()<EOL>


return dis.opmap[name]<EOL>

Return the opcode by name from the dis module.


s = set()<EOL>for name in names:<EOL><INDENT>try:<EOL><INDENT>s.add(_opcode(name))<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return s<EOL>

Return a set of opcodes by the names in `names`.


def __init__(self, text=None, filename=None, exclude=None):

assert text or filename, "<STR_LIT>"<EOL>self.filename = filename or "<STR_LIT>"<EOL>self.text = text<EOL>if not self.text:<EOL><INDENT>try:<EOL><INDENT>sourcef = open_source(self.filename)<EOL>try:<EOL><INDENT>self.text = sourcef.read()<EOL><DEDENT>finally:<EOL><INDENT>sourcef.close()<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>_, err, _ = sys.exc_info()<EOL>raise NoSource(<EOL>"<STR_LIT>" % (self.filename, err)<EOL>)<EOL><DEDENT><DEDENT>if self.text and ord(self.text[<NUM_LIT:0>]) == <NUM_LIT>:<EOL><INDENT>self.text = self.text[<NUM_LIT:1>:]<EOL><DEDENT>self.exclude = exclude<EOL>self.show_tokens = False<EOL>self.lines = self.text.split('<STR_LIT:\n>')<EOL>self.excluded = set()<EOL>self.docstrings = set()<EOL>self.classdefs = set()<EOL>self.multiline = {}<EOL>self.statement_starts = set()<EOL>self._byte_parser = None<EOL>

Source can be provided as `text`, the text itself, or `filename`, from
which the text will be read.  Excluded lines are those that match
`exclude`, a regex.


if not self._byte_parser:<EOL><INDENT>self._byte_parser =ByteParser(text=self.text, filename=self.filename)<EOL><DEDENT>return self._byte_parser<EOL>


regex_c = re.compile(join_regex(regexes))<EOL>matches = set()<EOL>for i, ltext in enumerate(self.lines):<EOL><INDENT>if regex_c.search(ltext):<EOL><INDENT>matches.add(i+<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return matches<EOL>

Find the lines matching one of a list of regexes.

        Returns a set of line numbers, the lines that contain a match for one
        of the regexes in `regexes`.  The entire line needn't match, just a
        part of it.


<EOL>if self.exclude:<EOL><INDENT>self.excluded = self.lines_matching(self.exclude)<EOL><DEDENT>indent = <NUM_LIT:0><EOL>exclude_indent = <NUM_LIT:0><EOL>excluding = False<EOL>prev_toktype = token.INDENT<EOL>first_line = None<EOL>empty = True<EOL>tokgen = generate_tokens(self.text)<EOL>for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen:<EOL><INDENT>if self.show_tokens:                <EOL><INDENT>print("<STR_LIT>" % (<EOL>tokenize.tok_name.get(toktype, toktype),<EOL>nice_pair((slineno, elineno)), ttext, ltext<EOL>))<EOL><DEDENT>if toktype == token.INDENT:<EOL><INDENT>indent += <NUM_LIT:1><EOL><DEDENT>elif toktype == token.DEDENT:<EOL><INDENT>indent -= <NUM_LIT:1><EOL><DEDENT>elif toktype == token.NAME and ttext == '<STR_LIT:class>':<EOL><INDENT>self.classdefs.add(slineno)<EOL><DEDENT>elif toktype == token.OP and ttext == '<STR_LIT::>':<EOL><INDENT>if not excluding and elineno in self.excluded:<EOL><INDENT>exclude_indent = indent<EOL>excluding = True<EOL><DEDENT><DEDENT>elif toktype == token.STRING and prev_toktype == token.INDENT:<EOL><INDENT>self.docstrings.update(range(slineno, elineno+<NUM_LIT:1>))<EOL><DEDENT>elif toktype == token.NEWLINE:<EOL><INDENT>if first_line is not None and elineno != first_line:<EOL><INDENT>rng = (first_line, elineno)<EOL>for l in range(first_line, elineno+<NUM_LIT:1>):<EOL><INDENT>self.multiline[l] = rng<EOL><DEDENT><DEDENT>first_line = None<EOL><DEDENT>if ttext.strip() and toktype != tokenize.COMMENT:<EOL><INDENT>empty = False<EOL>if first_line is None:<EOL><INDENT>first_line = slineno<EOL>if excluding and indent <= exclude_indent:<EOL><INDENT>excluding = False<EOL><DEDENT>if excluding:<EOL><INDENT>self.excluded.add(elineno)<EOL><DEDENT><DEDENT><DEDENT>prev_toktype = toktype<EOL><DEDENT>if not empty:<EOL><INDENT>self.statement_starts.update(self.byte_parser._find_statements())<EOL><DEDENT>

Parse the source to find the interesting facts about its lines.

        A handful of member fields are updated.


rng = self.multiline.get(line)<EOL>if rng:<EOL><INDENT>first_line = rng[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>first_line = line<EOL><DEDENT>return first_line<EOL>

Return the first line number of the statement including `line`.


ignore = set()<EOL>for ign in ignores:<EOL><INDENT>ignore.update(ign)<EOL><DEDENT>lset = set()<EOL>for l in lines:<EOL><INDENT>if l in ignore:<EOL><INDENT>continue<EOL><DEDENT>new_l = self.first_line(l)<EOL>if new_l not in ignore:<EOL><INDENT>lset.add(new_l)<EOL><DEDENT><DEDENT>return lset<EOL>

Map the line numbers in `lines` to the correct first line of the
        statement.

        Skip any line mentioned in any of the sequences in `ignores`.

        Returns a set of the first lines.


try:<EOL><INDENT>self._raw_parse()<EOL><DEDENT>except (tokenize.TokenError, IndentationError):<EOL><INDENT>_, tokerr, _ = sys.exc_info()<EOL>msg, lineno = tokerr.args<EOL>raise NotPython(<EOL>"<STR_LIT>" %<EOL>(self.filename, msg, lineno)<EOL>)<EOL><DEDENT>excluded_lines = self.first_lines(self.excluded)<EOL>lines = self.first_lines(<EOL>self.statement_starts,<EOL>excluded_lines,<EOL>self.docstrings<EOL>)<EOL>return lines, excluded_lines<EOL>

Parse source text to find executable lines, excluded lines, etc.

        Return values are 1) a set of executable line numbers, and 2) a set of
        excluded line numbers.

        Reported line numbers are normalized to the first line of multi-line
        statements.


all_arcs = []<EOL>for l1, l2 in self.byte_parser._all_arcs():<EOL><INDENT>fl1 = self.first_line(l1)<EOL>fl2 = self.first_line(l2)<EOL>if fl1 != fl2:<EOL><INDENT>all_arcs.append((fl1, fl2))<EOL><DEDENT><DEDENT>return sorted(all_arcs)<EOL>

Get information about the arcs available in the code.

        Returns a sorted list of line number pairs.  Line numbers have been
        normalized to the first line of multiline statements.


excluded_lines = self.first_lines(self.excluded)<EOL>exit_counts = {}<EOL>for l1, l2 in self.arcs():<EOL><INDENT>if l1 < <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if l1 in excluded_lines:<EOL><INDENT>continue<EOL><DEDENT>if l2 in excluded_lines:<EOL><INDENT>continue<EOL><DEDENT>if l1 not in exit_counts:<EOL><INDENT>exit_counts[l1] = <NUM_LIT:0><EOL><DEDENT>exit_counts[l1] += <NUM_LIT:1><EOL><DEDENT>for l in self.classdefs:<EOL><INDENT>if l in exit_counts:<EOL><INDENT>exit_counts[l] -= <NUM_LIT:1><EOL><DEDENT><DEDENT>return exit_counts<EOL>

Get a mapping from line numbers to count of exits from that line.

        Excluded lines are excluded.


children = CodeObjects(self.code)<EOL>return [ByteParser(code=c, text=self.text) for c in children]<EOL>

Iterate over all the code objects nested within this one.

        The iteration includes `self` as its first value.


<EOL>byte_increments = bytes_to_ints(self.code.co_lnotab[<NUM_LIT:0>::<NUM_LIT:2>])<EOL>line_increments = bytes_to_ints(self.code.co_lnotab[<NUM_LIT:1>::<NUM_LIT:2>])<EOL>last_line_num = None<EOL>line_num = self.code.co_firstlineno<EOL>byte_num = <NUM_LIT:0><EOL>for byte_incr, line_incr in zip(byte_increments, line_increments):<EOL><INDENT>if byte_incr:<EOL><INDENT>if line_num != last_line_num:<EOL><INDENT>yield (byte_num, line_num)<EOL>last_line_num = line_num<EOL><DEDENT>byte_num += byte_incr<EOL><DEDENT>line_num += line_incr<EOL><DEDENT>if line_num != last_line_num:<EOL><INDENT>yield (byte_num, line_num)<EOL><DEDENT>

Map byte offsets to line numbers in `code`.

        Uses co_lnotab described in Python/compile.c to map byte offsets to
        line numbers.  Produces a sequence: (b0, l0), (b1, l1), ...

        Only byte offsets that correspond to line numbers are included in the
        results.


for bp in self.child_parsers():<EOL><INDENT>for _, l in bp._bytes_lines():<EOL><INDENT>yield l<EOL><DEDENT><DEDENT>

Find the statements in `self.code`.

        Produce a sequence of line numbers that start statements.  Recurses
        into all code objects reachable from `self.code`.


blocks = "<STR_LIT:U+002CU+0020>".join(<EOL>["<STR_LIT>" % (dis.opname[b[<NUM_LIT:0>]], b[<NUM_LIT:1>]) for b in block_stack]<EOL>)<EOL>return "<STR_LIT:[>" + blocks + "<STR_LIT:]>"<EOL>

Get a string version of `block_stack`, for debugging.


<EOL>chunks = []<EOL>chunk = None<EOL>bytes_lines_map = dict(self._bytes_lines())<EOL>block_stack = []<EOL>ignore_branch = <NUM_LIT:0><EOL>ult = penult = None<EOL>jump_to = set()<EOL>bytecodes = list(ByteCodes(self.code.co_code))<EOL>for bc in bytecodes:<EOL><INDENT>if bc.jump_to >= <NUM_LIT:0>:<EOL><INDENT>jump_to.add(bc.jump_to)<EOL><DEDENT><DEDENT>chunk_lineno = <NUM_LIT:0><EOL>for bc in bytecodes:<EOL><INDENT>start_new_chunk = False<EOL>first_chunk = False<EOL>if bc.offset in bytes_lines_map:<EOL><INDENT>start_new_chunk = True<EOL>chunk_lineno = bytes_lines_map[bc.offset]<EOL>first_chunk = True<EOL><DEDENT>elif bc.offset in jump_to:<EOL><INDENT>start_new_chunk = True<EOL><DEDENT>elif bc.op in OPS_CHUNK_BEGIN:<EOL><INDENT>start_new_chunk = True<EOL><DEDENT>if not chunk or start_new_chunk:<EOL><INDENT>if chunk:<EOL><INDENT>chunk.exits.add(bc.offset)<EOL><DEDENT>chunk = Chunk(bc.offset, chunk_lineno, first_chunk)<EOL>chunks.append(chunk)<EOL><DEDENT>if bc.jump_to >= <NUM_LIT:0> and bc.op not in OPS_NO_JUMP:<EOL><INDENT>if ignore_branch:<EOL><INDENT>ignore_branch -= <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>chunk.exits.add(bc.jump_to)<EOL><DEDENT><DEDENT>if bc.op in OPS_CODE_END:<EOL><INDENT>chunk.exits.add(-self.code.co_firstlineno)<EOL><DEDENT>if bc.op in OPS_PUSH_BLOCK:<EOL><INDENT>block_stack.append((bc.op, bc.jump_to))<EOL><DEDENT>if bc.op in OPS_POP_BLOCK:<EOL><INDENT>block_stack.pop()<EOL><DEDENT>if bc.op in OPS_CHUNK_END:<EOL><INDENT>if bc.op == OP_BREAK_LOOP:<EOL><INDENT>chunk.exits.add(block_stack[-<NUM_LIT:1>][<NUM_LIT:1>])<EOL><DEDENT>chunk = None<EOL><DEDENT>if bc.op == OP_END_FINALLY:<EOL><INDENT>for block in reversed(block_stack):<EOL><INDENT>if block[<NUM_LIT:0>] in OPS_EXCEPT_BLOCKS:<EOL><INDENT>chunk.exits.add(block[<NUM_LIT:1>])<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if bc.op == OP_COMPARE_OP and bc.arg == COMPARE_EXCEPTION:<EOL><INDENT>ignore_branch += <NUM_LIT:1><EOL><DEDENT>penult = ult<EOL>ult = bc<EOL><DEDENT>if chunks:<EOL><INDENT>if ult and penult:<EOL><INDENT>if penult.op == OP_LOAD_CONST and ult.op == OP_RETURN_VALUE:<EOL><INDENT>if self.code.co_consts[penult.arg] is None:<EOL><INDENT>if chunks[-<NUM_LIT:1>].byte != penult.offset:<EOL><INDENT>ex = -self.code.co_firstlineno<EOL>last_chunk = chunks[-<NUM_LIT:1>]<EOL>last_chunk.exits.remove(ex)<EOL>last_chunk.exits.add(penult.offset)<EOL>chunk = Chunk(<EOL>penult.offset, last_chunk.line, False<EOL>)<EOL>chunk.exits.add(ex)<EOL>chunks.append(chunk)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>chunks[-<NUM_LIT:1>].length = bc.next_offset - chunks[-<NUM_LIT:1>].byte <EOL>for i in range(len(chunks)-<NUM_LIT:1>):<EOL><INDENT>chunks[i].length = chunks[i+<NUM_LIT:1>].byte - chunks[i].byte<EOL><DEDENT><DEDENT>return chunks<EOL>

Split the code object into a list of `Chunk` objects.

        Each chunk is only entered at its first instruction, though there can
        be many exits from a chunk.

        Returns a list of `Chunk` objects.


<EOL>starts = set([ch.byte for ch in chunks])<EOL>for ch in chunks:<EOL><INDENT>assert all([(ex in starts or ex < <NUM_LIT:0>) for ex in ch.exits])<EOL><DEDENT>

Validate the rule that chunks have a single entrance.


chunks = self._split_into_chunks()<EOL>byte_chunks = dict([(c.byte, c) for c in chunks])<EOL>yield (-<NUM_LIT:1>, byte_chunks[<NUM_LIT:0>].line)<EOL>for chunk in chunks:<EOL><INDENT>if not chunk.first:<EOL><INDENT>continue<EOL><DEDENT>chunks_considered = set()<EOL>chunks_to_consider = [chunk]<EOL>while chunks_to_consider:<EOL><INDENT>this_chunk = chunks_to_consider.pop()<EOL>chunks_considered.add(this_chunk)<EOL>for ex in this_chunk.exits:<EOL><INDENT>if ex < <NUM_LIT:0>:<EOL><INDENT>yield (chunk.line, ex)<EOL><DEDENT>else:<EOL><INDENT>next_chunk = byte_chunks[ex]<EOL>if next_chunk in chunks_considered:<EOL><INDENT>continue<EOL><DEDENT>backward_jump = next_chunk.byte < this_chunk.byte<EOL>if next_chunk.first or backward_jump:<EOL><INDENT>if next_chunk.line != chunk.line:<EOL><INDENT>yield (chunk.line, next_chunk.line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>chunks_to_consider.append(next_chunk)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>

Find the executable arcs in the code.

        Yields pairs: (from,to).  From and to are integer line numbers.  If
        from is < 0, then the arc is an entrance into the code object.  If to
        is < 0, the arc is an exit from the code object.


chunks = []<EOL>for bp in self.child_parsers():<EOL><INDENT>chunks.extend(bp._split_into_chunks())<EOL><DEDENT>return chunks<EOL>

Returns a list of `Chunk` objects for this code and its children.

        See `_split_into_chunks` for details.


arcs = set()<EOL>for bp in self.child_parsers():<EOL><INDENT>arcs.update(bp._arcs())<EOL><DEDENT>return arcs<EOL>

Get the set of all arcs in this code object and its children.

        See `_arcs` for details.


if text != self.last_text:<EOL><INDENT>self.last_text = text<EOL>self.last_tokens = list(<EOL>tokenize.generate_tokens(StringIO(text).readline)<EOL>)<EOL><DEDENT>return self.last_tokens<EOL>

A stand-in for `tokenize.generate_tokens`.


path = os.path.expandvars(os.path.expanduser(filename))<EOL>path = os.path.abspath(os.path.realpath(path))<EOL>path = actual_path(path)<EOL>return path<EOL>

Return the absolute normalized form of `filename`.


return ntpath.isabs(filename) or posixpath.isabs(filename)<EOL>

Is `filename` an absolute path on any OS?


prepped = []<EOL>for p in patterns or []:<EOL><INDENT>if p.startswith("<STR_LIT:*>") or p.startswith("<STR_LIT:?>"):<EOL><INDENT>prepped.append(p)<EOL><DEDENT>else:<EOL><INDENT>prepped.append(abs_file(p))<EOL><DEDENT><DEDENT>return prepped<EOL>

Prepare the file patterns for use in a `FnmatchMatcher`.

    If a pattern starts with a wildcard, it is used as a pattern
    as-is.  If it does not start with a wildcard, then it is made
    absolute with the current directory.

    If `patterns` is None, an empty list is returned.


sep_match = re.search(r"<STR_LIT>", s)<EOL>if sep_match:<EOL><INDENT>the_sep = sep_match.group(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>the_sep = os.sep<EOL><DEDENT>return the_sep<EOL>

Find the path separator used in this string, or os.sep if none.


for i, (dirpath, dirnames, filenames) in enumerate(os.walk(dirname)):<EOL><INDENT>if i > <NUM_LIT:0> and '<STR_LIT>' not in filenames:<EOL><INDENT>del dirnames[:]<EOL>continue<EOL><DEDENT>for filename in filenames:<EOL><INDENT>if re.match(r"<STR_LIT>", filename):<EOL><INDENT>yield os.path.join(dirpath, filename)<EOL><DEDENT><DEDENT><DEDENT>

Yield all of the importable Python files in `dirname`, recursively.

    To be importable, the files have to be in a directory with a __init__.py,
    except for `dirname` itself, which isn't required to have one.  The
    assumption is that `dirname` was specified directly, so the user knows
    best, but subdirectories are checked for a __init__.py to be sure we only
    find the importable files.


fnorm = os.path.normcase(filename)<EOL>if fnorm.startswith(self.relative_dir):<EOL><INDENT>filename = filename[len(self.relative_dir):]<EOL><DEDENT>return filename<EOL>

Return the relative form of `filename`.

        The filename will be relative to the current directory when the
        `FileLocator` was constructed.


if filename not in self.canonical_filename_cache:<EOL><INDENT>if not os.path.isabs(filename):<EOL><INDENT>for path in [os.curdir] + sys.path:<EOL><INDENT>if path is None:<EOL><INDENT>continue<EOL><DEDENT>f = os.path.join(path, filename)<EOL>if os.path.exists(f):<EOL><INDENT>filename = f<EOL>break<EOL><DEDENT><DEDENT><DEDENT>cf = abs_file(filename)<EOL>self.canonical_filename_cache[filename] = cf<EOL><DEDENT>return self.canonical_filename_cache[filename]<EOL>

Return a canonical filename for `filename`.

        An absolute path with no redundant components and normalized case.


import zipimport<EOL>markers = ['<STR_LIT>'+os.sep, '<STR_LIT>'+os.sep]<EOL>for marker in markers:<EOL><INDENT>if marker in filename:<EOL><INDENT>parts = filename.split(marker)<EOL>try:<EOL><INDENT>zi = zipimport.zipimporter(parts[<NUM_LIT:0>]+marker[:-<NUM_LIT:1>])<EOL><DEDENT>except zipimport.ZipImportError:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>data = zi.get_data(parts[<NUM_LIT:1>])<EOL><DEDENT>except IOError:<EOL><INDENT>continue<EOL><DEDENT>return to_string(data)<EOL><DEDENT><DEDENT>return None<EOL>

Get data from `filename` if it is a zip file path.

        Returns the string data read from the zip file, or None if no zip file
        could be found or `filename` isn't in it.  The data returned will be
        an empty string if the file is empty.


return self.dirs<EOL>

A list of strings for displaying when dumping state.


self.dirs.append(directory)<EOL>

Add another directory to the list we match for.


for d in self.dirs:<EOL><INDENT>if fpath.startswith(d):<EOL><INDENT>if fpath == d:<EOL><INDENT>return True<EOL><DEDENT>if fpath[len(d)] == os.sep:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Does `fpath` indicate a file in one of our trees?


return self.pats<EOL>


for pat in self.pats:<EOL><INDENT>if fnmatch.fnmatch(fpath, pat):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Does `fpath` match one of our filename patterns?


<EOL>pattern = pattern.rstrip(r"<STR_LIT>")<EOL>if pattern.endswith("<STR_LIT:*>"):<EOL><INDENT>raise CoverageException("<STR_LIT>")<EOL><DEDENT>pattern_sep = sep(pattern)<EOL>if not pattern.startswith('<STR_LIT:*>') and not isabs_anywhere(pattern):<EOL><INDENT>pattern = abs_file(pattern)<EOL><DEDENT>pattern += pattern_sep<EOL>regex_pat = fnmatch.translate(pattern).replace(r'<STR_LIT>', '<STR_LIT:(>')<EOL>if regex_pat.endswith("<STR_LIT:$>"):<EOL><INDENT>regex_pat = regex_pat[:-<NUM_LIT:1>]<EOL><DEDENT>regex_pat = regex_pat.replace(r"<STR_LIT>", r"<STR_LIT>")<EOL>regex = re.compile(r"<STR_LIT>" + regex_pat)<EOL>result_sep = sep(result)<EOL>result = result.rstrip(r"<STR_LIT>") + result_sep<EOL>self.aliases.append((regex, result, pattern_sep, result_sep))<EOL>

Add the `pattern`/`result` pair to the list of aliases.

        `pattern` is an `fnmatch`-style pattern.  `result` is a simple
        string.  When mapping paths, if a path starts with a match against
        `pattern`, then that match is replaced with `result`.  This models
        isomorphic source trees being rooted at different places on two
        different machines.

        `pattern` can't end with a wildcard component, since that would
        match an entire tree, and not just its root.


for regex, result, pattern_sep, result_sep in self.aliases:<EOL><INDENT>m = regex.match(path)<EOL>if m:<EOL><INDENT>new = path.replace(m.group(<NUM_LIT:0>), result)<EOL>if pattern_sep != result_sep:<EOL><INDENT>new = new.replace(pattern_sep, result_sep)<EOL><DEDENT>if self.locator:<EOL><INDENT>new = self.locator.canonical_filename(new)<EOL><DEDENT>return new<EOL><DEDENT><DEDENT>return path<EOL>

Map `path` through the aliases.

        `path` is checked against all of the patterns.  The first pattern to
        match is used to replace the root of the path with the result root.
        Only one pattern is ever used.  If no patterns match, `path` is
        returned unchanged.

        The separator style in the result is made to match that of the result
        in the alias.


parts = s.split(sep)<EOL>return sep.join(parts[:-<NUM_LIT:1>]), parts[-<NUM_LIT:1>]<EOL>

The same as s.rsplit(sep, 1), but works in 2.3


openfile = None<EOL>glo, loc = globals(), locals()<EOL>try:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:.>' in modulename:<EOL><INDENT>packagename, name = rsplit1(modulename, '<STR_LIT:.>')<EOL>package = __import__(packagename, glo, loc, ['<STR_LIT>'])<EOL>searchpath = package.__path__<EOL><DEDENT>else:<EOL><INDENT>packagename, name = None, modulename<EOL>searchpath = None  <EOL><DEDENT>openfile, pathname, _ = imp.find_module(name, searchpath)<EOL>if openfile is None and pathname is None:<EOL><INDENT>raise NoSource(<EOL>"<STR_LIT>" % modulename<EOL>)<EOL><DEDENT>if openfile is None:<EOL><INDENT>packagename = modulename<EOL>name = '<STR_LIT:__main__>'<EOL>package = __import__(packagename, glo, loc, ['<STR_LIT>'])<EOL>searchpath = package.__path__<EOL>openfile, pathname, _ = imp.find_module(name, searchpath)<EOL><DEDENT><DEDENT>except ImportError:<EOL><INDENT>_, err, _ = sys.exc_info()<EOL>raise NoSource(str(err))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if openfile:<EOL><INDENT>openfile.close()<EOL><DEDENT><DEDENT>pathname = os.path.abspath(pathname)<EOL>args[<NUM_LIT:0>] = pathname<EOL>run_python_file(pathname, args, package=packagename)<EOL>

Run a python module, as though with ``python -m name args...``.

    `modulename` is the name of the module, possibly a dot-separated name.
    `args` is the argument array to present as sys.argv, including the first
    element naming the module being executed.


def run_python_file(filename, args, package=None):

<EOL>old_main_mod = sys.modules['<STR_LIT:__main__>']<EOL>main_mod = imp.new_module('<STR_LIT:__main__>')<EOL>sys.modules['<STR_LIT:__main__>'] = main_mod<EOL>main_mod.__file__ = filename<EOL>if package:<EOL><INDENT>main_mod.__package__ = package<EOL><DEDENT>main_mod.__builtins__ = BUILTINS<EOL>old_argv = sys.argv<EOL>sys.argv = args<EOL>try:<EOL><INDENT>if filename.endswith("<STR_LIT>") or filename.endswith("<STR_LIT>"):<EOL><INDENT>code = make_code_from_pyc(filename)<EOL><DEDENT>else:<EOL><INDENT>code = make_code_from_py(filename)<EOL><DEDENT>try:<EOL><INDENT>exec_code_object(code, main_mod.__dict__)<EOL><DEDENT>except SystemExit:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>typ, err, tb = sys.exc_info()<EOL>raise ExceptionDuringRun(typ, err, tb.tb_next.tb_next)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>sys.modules['<STR_LIT:__main__>'] = old_main_mod<EOL>sys.argv = old_argv<EOL><DEDENT>

Run a python file as if it were the main program on the command line.

    `filename` is the path to the file to execute, it need not be a .py file.
    `args` is the argument array to present as sys.argv, including the first
    element naming the file being executed.  `package` is the name of the
    enclosing package, if any.


<EOL>try:<EOL><INDENT>source_file = open_source(filename)<EOL><DEDENT>except IOError:<EOL><INDENT>raise NoSource("<STR_LIT>" % filename)<EOL><DEDENT>try:<EOL><INDENT>source = source_file.read()<EOL><DEDENT>finally:<EOL><INDENT>source_file.close()<EOL><DEDENT>if not source or source[-<NUM_LIT:1>] != '<STR_LIT:\n>':<EOL><INDENT>source += '<STR_LIT:\n>'<EOL><DEDENT>code = compile(source, filename, "<STR_LIT>")<EOL>return code<EOL>

Get source from `filename` and make a code object of it.


try:<EOL><INDENT>fpyc = open(filename, "<STR_LIT:rb>")<EOL><DEDENT>except IOError:<EOL><INDENT>raise NoCode("<STR_LIT>" % filename)<EOL><DEDENT>try:<EOL><INDENT>magic = fpyc.read(<NUM_LIT:4>)<EOL>if magic != imp.get_magic():<EOL><INDENT>raise NoCode("<STR_LIT>")<EOL><DEDENT>fpyc.read(<NUM_LIT:4>)            <EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:3>):<EOL><INDENT>fpyc.read(<NUM_LIT:4>)<EOL><DEDENT>code = marshal.load(fpyc)<EOL><DEDENT>finally:<EOL><INDENT>fpyc.close()<EOL><DEDENT>return code<EOL>


source = None<EOL>base, ext = os.path.splitext(filename)<EOL>TRY_EXTS = {<EOL>'<STR_LIT>':  ['<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>}<EOL>try_exts = TRY_EXTS.get(ext)<EOL>if not try_exts:<EOL><INDENT>return filename, None<EOL><DEDENT>for try_ext in try_exts:<EOL><INDENT>try_filename = base + try_ext<EOL>if os.path.exists(try_filename):<EOL><INDENT>return try_filename, None<EOL><DEDENT>source = self.coverage.file_locator.get_zip_data(try_filename)<EOL>if source:<EOL><INDENT>return try_filename, source<EOL><DEDENT><DEDENT>raise NoSource("<STR_LIT>" % filename)<EOL>

Find the source for `filename`.

        Returns two values: the actual filename, and the source.

        The source returned depends on which of these cases holds:

            * The filename seems to be a non-source file: returns None

            * The filename is a source file, and actually exists: returns None.

            * The filename is a source file, and is in a zip file or egg:
              returns the source.

            * The filename is a source file, but couldn't be found: raises
              `NoSource`.


return format_lines(self.statements, self.missing)<EOL>

The missing line numbers, formatted nicely.

        Returns a string like "1-2, 5-11, 13-14".


return self.coverage.data.has_arcs()<EOL>


arcs = self.parser.arcs()<EOL>return arcs<EOL>

Returns a sorted list of the arcs in the code.


executed = self.coverage.data.executed_arcs(self.filename)<EOL>m2fl = self.parser.first_line<EOL>executed = [(m2fl(l1), m2fl(l2)) for (l1,l2) in executed]<EOL>return sorted(executed)<EOL>

Returns a sorted list of the arcs actually executed in the code.


possible = self.arc_possibilities()<EOL>executed = self.arcs_executed()<EOL>missing = [<EOL>p for p in possible<EOL>if p not in executed<EOL>and p[<NUM_LIT:0>] not in self.no_branch<EOL>]<EOL>return sorted(missing)<EOL>

Returns a sorted list of the arcs in the code not executed.


possible = self.arc_possibilities()<EOL>executed = self.arcs_executed()<EOL>unpredicted = [<EOL>e for e in executed<EOL>if e not in possible<EOL>and e[<NUM_LIT:0>] != e[<NUM_LIT:1>]<EOL>]<EOL>return sorted(unpredicted)<EOL>

Returns a sorted list of the executed arcs missing from the code.


exit_counts = self.parser.exit_counts()<EOL>return [l1 for l1,count in iitems(exit_counts) if count > <NUM_LIT:1>]<EOL>

Returns a list of line numbers that have more than one exit.


exit_counts = self.parser.exit_counts()<EOL>return sum([count for count in exit_counts.values() if count > <NUM_LIT:1>])<EOL>


missing = self.arcs_missing()<EOL>branch_lines = set(self.branch_lines())<EOL>mba = {}<EOL>for l1, l2 in missing:<EOL><INDENT>if l1 in branch_lines:<EOL><INDENT>if l1 not in mba:<EOL><INDENT>mba[l1] = []<EOL><DEDENT>mba[l1].append(l2)<EOL><DEDENT><DEDENT>return mba<EOL>

Return arcs that weren't executed from branch lines.

        Returns {l1:[l2a,l2b,...], ...}


exit_counts = self.parser.exit_counts()<EOL>missing_arcs = self.missing_branch_arcs()<EOL>stats = {}<EOL>for lnum in self.branch_lines():<EOL><INDENT>exits = exit_counts[lnum]<EOL>try:<EOL><INDENT>missing = len(missing_arcs[lnum])<EOL><DEDENT>except KeyError:<EOL><INDENT>missing = <NUM_LIT:0><EOL><DEDENT>stats[lnum] = (exits, exits - missing)<EOL><DEDENT>return stats<EOL>

Get stats about branches.

        Returns a dict mapping line numbers to a tuple:
        (total_exits, taken_exits).


assert <NUM_LIT:0> <= precision < <NUM_LIT:10><EOL>cls._precision = precision<EOL>cls._near0 = <NUM_LIT:1.0> / <NUM_LIT:10>**precision<EOL>cls._near100 = <NUM_LIT> - cls._near0<EOL>

Set the number of decimal places used to report percentages.


return self.n_statements - self.n_missing<EOL>

Returns the number of executed statements.


return self.n_branches - self.n_missing_branches<EOL>

Returns the number of executed branches.


if self.n_statements > <NUM_LIT:0>:<EOL><INDENT>pc_cov = (<NUM_LIT> * (self.n_executed + self.n_executed_branches) /<EOL>(self.n_statements + self.n_branches))<EOL><DEDENT>else:<EOL><INDENT>pc_cov = <NUM_LIT><EOL><DEDENT>return pc_cov<EOL>

Returns a single percentage value for coverage.