"""Cache lines from files.
This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
__all__ = ["getline", "clearcache", "checkcache"]
def getline(filename, lineno, module_globals=None):
lines = getlines(filename, module_globals)
if 1 <= lineno <= len(lines):
"""Clear the cache entirely."""
def getlines(filename, module_globals=None):
"""Get the lines for a file from the cache.
Update the cache if it doesn't contain an entry for this file already."""
return cache[filename][2]
return updatecache(filename, module_globals)
def checkcache(filename=None):
"""Discard cache entries that are out of date.
(This is not checked upon each call!)"""
for filename in filenames:
size, mtime, lines, fullname = cache[filename]
continue # no-op for files loaded via a __loader__
if size != stat.st_size or mtime != stat.st_mtime:
def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if not filename or (filename.startswith('<') and filename.endswith('>')):
# Try for a __loader__, if available
if module_globals and '__loader__' in module_globals:
name = module_globals.get('__name__')
loader = module_globals['__loader__']
get_source = getattr(loader, 'get_source', None)
except (ImportError, IOError):
# No luck, the PEP302 loader cannot find the source
[line+'\n' for line in data.splitlines()], fullname
return cache[filename][2]
# Try looking through the module search path, which is only useful
# when handling a relative filename.
if os.path.isabs(filename):
# When using imputil, sys.path may contain things other than
# strings; ignore them when it happens.
fullname = os.path.join(dirname, basename)
except (TypeError, AttributeError):
# Not sufficiently string-like to do anything useful with.
with open(fullname, 'rU') as fp:
if lines and not lines[-1].endswith('\n'):
size, mtime = stat.st_size, stat.st_mtime
cache[filename] = size, mtime, lines, fullname