1 """Cache lines from files.
3 This is intended to read lines from modules imported -- hence if a filename
4 is not found, it will look down the module search path for a file by
12 __all__
= ["getline", "clearcache", "checkcache"]
14 def getline(filename
, lineno
, module_globals
=None):
15 lines
= getlines(filename
, module_globals
)
16 if 1 <= lineno
<= len(lines
):
17 return lines
[lineno
-1]
24 cache
= {} # The cache
28 """Clear the cache entirely."""
34 def getlines(filename
, module_globals
=None):
35 """Get the lines for a file from the cache.
36 Update the cache if it doesn't contain an entry for this file already."""
39 return cache
[filename
][2]
41 return updatecache(filename
, module_globals
)
44 def checkcache(filename
=None):
45 """Discard cache entries that are out of date.
46 (This is not checked upon each call!)"""
49 filenames
= list(cache
.keys())
52 filenames
= [filename
]
56 for filename
in filenames
:
57 size
, mtime
, lines
, fullname
= cache
[filename
]
59 continue # no-op for files loaded via a __loader__
61 stat
= os
.stat(fullname
)
65 if size
!= stat
.st_size
or mtime
!= stat
.st_mtime
:
69 def updatecache(filename
, module_globals
=None):
70 """Update a cache entry and return its list of lines.
71 If something's wrong, print a message, discard the cache entry,
72 and return an empty list."""
76 if not filename
or filename
[0] + filename
[-1] == '<>':
81 stat
= os
.stat(fullname
)
82 except os
.error
as msg
:
83 basename
= os
.path
.split(filename
)[1]
85 # Try for a __loader__, if available
86 if module_globals
and '__loader__' in module_globals
:
87 name
= module_globals
.get('__name__')
88 loader
= module_globals
['__loader__']
89 get_source
= getattr(loader
, 'get_source', None)
91 if name
and get_source
:
92 if basename
.startswith(name
.split('.')[-1]+'.'):
94 data
= get_source(name
)
95 except (ImportError, IOError):
99 # No luck, the PEP302 loader cannot find the source
104 [line
+'\n' for line
in data
.splitlines()], fullname
106 return cache
[filename
][2]
108 # Try looking through the module search path.
110 for dirname
in sys
.path
:
111 # When using imputil, sys.path may contain things other than
112 # strings; ignore them when it happens.
114 fullname
= os
.path
.join(dirname
, basename
)
115 except (TypeError, AttributeError):
116 # Not sufficiently string-like to do anything useful with.
120 stat
= os
.stat(fullname
)
126 ## print '*** Cannot stat', filename, ':', msg
128 ## print("Refreshing cache for %s..." % fullname)
130 fp
= open(fullname
, 'rU')
131 lines
= fp
.readlines()
133 except Exception as msg
:
134 ## print '*** Cannot open', fullname, ':', msg
137 for line
in lines
[:2]:
138 m
= re
.search(r
"coding[:=]\s*([-\w.]+)", line
)
143 lines
= [line
if isinstance(line
, str) else str(line
, coding
)
146 pass # Hope for the best
147 size
, mtime
= stat
.st_size
, stat
.st_mtime
148 cache
[filename
] = size
, mtime
, lines
, fullname